horace_vr
horace_vr

Reputation: 3166

Python regex with exclusion of a character

Having a list of texts:

l=["SOMETHING","SOME_1","SOM_1"]

I am looking for a regex pattern to match the first string, but not the second one:

This is what I tried, but does not work:

import re
l=["SOMETHING","SOME_1","SOM_1"]
find_pattern=re.compile("^SOM[A-Z]*[^_]")
for s in l:
    print bool(find_pattern.match(s))

I am expecting:

True
False
False

But I think the multiplication operand is not correct, because I get:

True
True
False

Upvotes: 1

Views: 48

Answers (2)

r.ook
r.ook

Reputation: 13858

Try this:

find_pattern = re.compile('^SOM[^_]*(?!\_)$')

for s in l:
    print(bool(find_pattern.match(s)))

# True
# False
# False

Sample and explanation here: https://regex101.com/r/DVzoww/1

Upvotes: 1

Paolo
Paolo

Reputation: 25999

import re
l=["SOMETHING","SOME_1","SOM_1"]
find_pattern=re.compile("^SOM[^_]*$")
for s in l:
    print bool(find_pattern.match(s))

Prints the expected result:

True
False
False

In the pattern, note the importance of the $ anchor. If this was not present, you would receive false positives.

Upvotes: 5

Related Questions