Jérèm Le Blond Jérèm Le Blond - 6 months ago 12
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

[a-zA-Z0-9_~+-]{1,64}


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:

((?!(TEST|SPECIFIC1|SPECIFIC2)).)*


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

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

^((?!(TEST|SPECIFIC1|SPECIFIC2))[a-zA-Z0-9_~+-]){1,64}$

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.