Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Include character in regex only if another character is there

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

11:32) 

Which I don’t want.

How can I solve this issue?

>Solution :

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 regex101‘s demo, and Debuggex‘s diagram:

Debuggex

A tad hairy!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading