How to have an exception in regular expression?

Viewed 34

I have a regex that can detect times format like 19:00 PST, But based on my regex 2021 PST is detected as a time. I don't wanna detect a date as a time. Here is my regex:

( |^|)\d{1,2}(?:[.:](\d\d))*\s*([aApP][.: ]?[mM][.: ]?|o['’]clock|afternoon)*\s* PST

The detection result based on regex101 is here:

enter image description here

How can I change this regex to detect 12 PST after bar12PST but not detect 2021 PST as a time?

Regext Link :https://regex101.com/r/zy193H/1/

2 Answers

The initial group ( |^|) is quite nonsensical, but it's not easy to understand what you wanted it to mean. Perhaps replace it with (^|\s|\D) to match either beginning of line or a space or a non-digit character.

Depending on what you actually want, \W might be closer to what you desire (it also doesn't match alphabetics or underscore), but perhaps clarify what the principle should be.

Assuming the rest of your regex is correct then you just need to trade ( |^|) for (^|(?<=\D)):

(^|(?<=\D))\d{1,2}(?:[.:](\d\d))*\s*([aApP][.: ]?[mM][.: ]?|o['’]clock|afternoon)*\s* PST
  • (^|(?<=\D)) - guarantee that behind me is the start of a line or not a digit

https://regex101.com/r/LgzGaJ/1

Related