Question

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!

Was it helpful?

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.

OTHER TIPS

You need something like this:

(?<!xyz )abc

Regular expression visualization

Debuggex Demo

But syntax will vary, depending on the language you are using. For example, this syntax won't work in JavaScript.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top