How can I make regular expression in python match only alphanumeric and not numerical or alphabet characters?
How do I make regular expressions in python match this13
or 13this
but not this
or 13
?
>>> re.search(r'[\w\d]+', 'this13') # returns this13 which is ok
>>> re.search(r'[\w\d]+', '13this') # returns 13this which is ok
>>> re.search(r'[\w\d]+', 'this') # returns this but I want empty string as result
>>> re.search(r'[\w\d]+', '13') # returns 13 but I want empty string as result
I would use an alternation here:
inp = ["this13", "13this", "this", "13"]
output = [bool(re.search(r'^(?:[a-z]+[0-9]+|[0-9]+[a-z]+)$', x, flags=re.I)) for x in inp]
print(output) # [True, True, False, False]
The regex pattern used above says to match:
^ from the start of the string
(?:
[a-z]+[0-9]+ letters followed by numbers
| OR
[0-9]+[a-z]+ numbers followed by letters
)
$ end of the string