3

Before posting this question I have gone through the Regex Wiki and the following SO questions as well:

How To Negate Regex

How to exclude a specific string constant?

Here is what I have gotten working, which is partially what I want:

(?!INVALID).*$

The first SO post actually solves my problem a little bit after editing the posted regex

The problem with what I have working is the regex fails when the word starts with INVALID

So basically :

  • TestINVALID will work
  • TestINVALID123 will work
  • INVALID will not match which is what I want so will work
  • But INVALIDTest will not work, it will not match

I want the regex to not match only and only if string exactly matches "INVALID"

Abdul Aziz Barkat
  • 19,475
  • 3
  • 20
  • 33
Nick Div
  • 5,338
  • 12
  • 65
  • 127

2 Answers2

2

You need to include $ in your negative look ahead:

^(?!INVALID$).*
           ^----------added "$" here

This prevents the entire input (not just the leading input) from being "ÌNVALID".

Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

You might want to try a tempered greedy token:

^(?:(?!INVALID).)+$

This invalidates all of the following but the last:

TestINVALID
TestINVALID123
INVALID
INVALIDTest
this one will be valid

See a demo on regex101.com and mind the multiline flag.


Having read you question again, it has gotten unclearer. Do you want to match lines where there is only the word INVALID in it? This can be achieved with simple string functions or (if you insist on using regular expressions):
^INVALID$ # look for INVALID from start to end of the line

See a demo for this one on regex101.com as well.

Jan
  • 42,290
  • 8
  • 54
  • 79
  • Thanks a lot for trying out the regex, and I apologize if the question was a bit unclear. Actually the requirement itself was a bit confusing so not sure if I phrased it well. Again, appreciate it. – Nick Div Jul 06 '16 at 15:32