javaregexstringexpression

Regular expression to exclude 2 words


I am using REGEX in Java, and I need to check if a string has one WORD without some certain words right before and after it.

I managed to create a regular expression which excludes the word after:

.*WORD(?! AFTER).*

With this expression, the string "bla bla WORD AFTER bla bla" will not match, but the string "bla bla WORD bla bla" will match.

I need the same behaviour for the previous word also. For example, the string "bla bla bla BEFORE WORD AFTER bla bla bla" shouldn't match, but the string "bla bla WORD bla bla" should.

I tried this:

.*(?!BEFORE )WORD(?! AFTER).*

Although the expression doesn't give any error, it doesn't have the expected behaviour. Instead, it works exactly the same as the first expression (without (?!BEFORE )). Any idea would be appreciated.


Solution

  • Try this (negative lookbehind (see Java API documentation for class Pattern):

    .*(?<!BEFORE )WORD(?! AFTER).*