Reputation: 3166
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:
TRUE
if the text starts with 'SOM' , possible some other characters, and no underscores; FALSE
if the text starts with 'SOM' and contains at least one underscore (somewhere inside the text, it does not matter where that underscore is)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
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
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