Computer >> Computer tutorials >  >> Programming >> Python

What is the Python regular expression to check if a string is alphanumeric?


For checking if a string consists only of alphanumerics using module regular expression or regex, we can call the re.match(regex, string) using the regex: "^[a-zA-Z0-9]+$". 

For example,

>>> bool(re.match('^[a-zA-Z0-9]+$', '789def'))
True
>>> bool(re.match('^[a-zA-Z0-9]+$', '789#%$def'))
False

re.match returns an object, to check if it exists or not, we need to convert it to a boolean using bool().