Search code examples
regexnegative-lookbehind

Find word that does not come after another word with RegEx


What is the RegEx pattern I should use in order to match a specific word that does not come after another specific word?

For example:

I'm looking for an "abc" that does not come after "xyz", so the following will match:

xxabc

p abc

And the following will not:

xyz abc

Thanks!


Solution

  • The easiest way is a negative lookbehind assertion:

    (?<!xyz)(?<!xyz )abc
    

    Your variation in spacing between letter groups, however, suggests that you might see some variation in distance between abc and xyz. If you only want to find abc if it is never preceded by xyz earlier in the string, then you may need something more along the lines of this:

    ^(?!xyz)*((?!xyz).)*abc
    

    The latter regular expression uses an equivalent of inverse matching rather than a negative lookbehind assertion.