Mahmoud Mahmoud - 3 months ago 8
Perl Question

Could not find the right regex pattern

I want to write a regular expression to match every word which :


  • Does not start with any of these 2 strings (TEMP_, TMP_)

  • Contains in the middle the string : LME999

  • Does not end with any of these 2 strings (.flag, _TEMP)

  • Before and After LME999, the string can have any alphanumeric character



I wrote this regular expression, but it does not work as expected

(?!TEMP_)+(?!TMP_)+(\w)+LME999+(\w)+((?!.flag)(?!_TEMP))


Here are some valid string:
StringLME999String

Answer

You can use this regex:

^(?!TE?MP_).*?LME999.*$(?<!\.flag|_TEMP)

RegEx Demo

RegEx Breakup:

^                   # line start
(?!TE?MP_)          # negative lookahead to assert failure if starts with TMP_ or TEMP_
.*?                 # match 0 or more of any char (lazy)
LME999              # match LME99
.*                  # match 0 or more of any char 
$                   # line end
(?<!\.flag|_TEMP)   # negative lookbehind to assert failure if ends with .flag or _TEMP
Comments