Search code examples
regexinclusion

RegExp help (working but need an exclusion)


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??


Solution

  • 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).*/