-2

I am need of some regex help.

I have a list like so:

/hours_3203
/hours_3204
/hours_3205
/hours_3206
/hours_3207
/hours_3208
/hours_3309
/hours_3310
/hours_3211

I am using this regex to find all entries that start with 32 or 33:

/hours_3[23]/

and this is working.

However I was thrown a curve ball when I was told I need to exclude hours_3211 from matching in this list.

How can I adjust my regex to match on all hours_3[23] but NOT match on /hours_3211?

Alternately, when I have a list like this:

/hours_3412
/hours_3413
/hours_3414
/hours_3415
/hours_3516
/hours_3517
/hours_3518
/hours_3519

I have been using a regex of:

/hours_3[45]/

to find all hours_34x and /hours_35x

How I can adjust this:

/hours_3[45]/

to find the above but also find/match on /hours_3211??

timolawl
  • 5,434
  • 13
  • 29
whispers
  • 962
  • 1
  • 22
  • 48

3 Answers3

4

How can I adjust my regex to match on all hours_3[23] but NOT match on hours_3211?

You can use insert a negative lookahead sub pattern:

/hours_3(?!211)[23]/

(?!211) is negative lookahead to disallow 211 after hours_3 thus disallowing hours_3211

anubhava
  • 761,203
  • 64
  • 569
  • 643
1

I'm assuming your adding 3211 to the second Regex which would be something like this ....

hours_(3[45]|3211)

The first one would be a negative lookahead

hours_3[23](?!11)
Chris Sullivan
  • 576
  • 5
  • 10
1

How can I adjust my regex to match on all hours_3[23] but NOT match on hours_3211?

Use negative lookahead (?!):

/hours_3(?!211)[23]/

How I can adjust /hours_3[45]/ to find the above but ALSO find/match on /hours_3211?

Use alternation |:

/hours_3(?:[45]|211)/

Edit:

More appropriately, the above only specifies if it matches or not. If you want the actual full match returned, you want to add .* to the end of the RegExp like so:

/hours_3(?!211)[23].*/
/hours_3(?:[45]|211).*/
timolawl
  • 5,434
  • 13
  • 29
  • Thanks for the answer to both parts! Everyone else still got up votes. these both also worked for me: /hours_3([45]|211)/ /hours_3(20|3)/ Not sure how much of a difference there is between them? (regex force is weak with this one!) HAHA... the more advanced regex still escapes me. – whispers May 02 '16 at 23:04
  • the `(?:)` is called a non-capture group. It is used to group without matching to output. I'm assuming this is JavaScript (correct me if I'm wrong), and so if you use regular grouping `()` and try to use `String.prototype.match()` for instance, then you will not only match the entire expression, but whatever is in `()` will also be outputted as the second match in the output. Using `(?:)` in this case means that only your entire match is returned. – timolawl May 02 '16 at 23:10
  • @whispers For `/hours_3(20|3)/` this is fine assuming you wouldn't want to match something like `hours_3210`, since you specify that a `0` must follow the `2`. – timolawl May 02 '16 at 23:11