Jérèm Le Blond Jérèm Le Blond - 2 years ago 76
Python Question

String matching a pattern and not containing some words

I'm looking for a regex which match words with a specific pattern (see below) but which doesn't contain one of three specific words

The pattern is


and the words I don't want to be contained in the whole word are 'TEST', 'SPECIFIC1' and 'SPECIFIC2'

So far, I found a regex to not match those words:


but I can't find how to combine those two regex.

For example:

TEST won't match
TES$ won't match
SPECIFIC1 won't match
NON-SPECIFIC2 won't match
SPECIFIC2 won't match
MATCHES will match
test will match

Does someone have an idea?

Answer Source

If you surround the expression with ^ and $ you can put the negative lookahead together with your character class to accomplish this.


Here's a demonstration. Note that this uses the flags global and multiline so I can have one match per row for demonstration purposes.

Without ^ and $ the pattern can just be shifted to avoid matching the forbidden strings.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download