regexregex-look-ahead

regex to ignore string ends with specific pattern


I am trying to write regex which should ignore any string ends with _numbers like (_1234)

like below

abc_def_1234 - should not match
abc_fgh - match
abc_ghj -  match
abc_ijk_2345 - not match

I am trying to use lookahead regex like below, but it's matching everything. Can someone please help me how I can achieve this?

\w+(?!_\d+)

Solution

  • Match words separated by underscores, but use a negative look ahead to exclude input that has the unwanted tail:

    ^(?!.*_\d+$)\w+(?<!_)$
    

    See live demo.

    The last look behind (which you can remove) is there to require that the last char is not an underscore - ie that the input is AFAICT well formed.