Home > Enterprise >  Include character in regex only if another character is there
Include character in regex only if another character is there

Time:09-14

I have this regular expression for finding time:

/ (\[|\(|)([0-1]?[0-9]|2[0-3])(:)[0-5][0-9](:[0-5][0-9])?(( ?am| ?pm|))(\]|\)|)/gi

Currently, it correctly identifies:

11:32
11:32 am
11:32 Am
11:32 AM
(11:32)
[11:32 am]

The only thing that doesn't work is that it includes the right bracket even if the left bracket is not there, for example it would include:

11:32) 

Which I don't want.

How can I solve this issue?

CodePudding user response:

I've "simplified" your question to match:

x
(x)
[x]

while ignoring:

x)
x]
(x
[x
[x)
(x]

I've come up with the following:

(?:^(?:(?=[^)\]] $)|\[(?=. \]$)|\((?=. \)$)))x[)\]]?$

See Debuggex

A tad hairy!

CodePudding user response:

I'm not sure on the final utility of this, but if you want to "find time", why do you need something so complicate ?

You did not specify if you need to find time for any format or only on right formated ones.

If you need to extract time for all syntax cases (non regarding the paranthesis nor the brackets) something simple as this snippet should do the trick

const regex = /.*(\d{2}:\d{2}).*/gim;
const str = `12:12
(12:12)
[12:12]
12:12)
12:12]
(12:12
[12:12
[12:12)
(12:12]
12:12 am
(12:12 am)
[12:12 am]
12:12 am)
12:12 am]
(12:12 am
[12:12 am
[12:12 am)
(12:12 am]`;
const subst = `$1`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

  • Related