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



In this article, we are going to focus on how to check if a string is alphanumeric using Regular expressions in Python.

Regular expressions are used in both the techniques. Import the re library and install it if it isn't already installed to use it. After importing the re library, we can use the regular expression "[a-zA-Z0-9]+$.".

This will return False if the string contains any special characters other than Alphabets and Numbers; otherwise, True will be returned.

Example 1

In the example given below, we are taking a string as input and checking if it is alphanumeric using Regular Expressions 

import re

str1 = "Tutorialspoint123"
print("The given string is")
print(str1)

print("Checking if the given string is alphanumeric")
print(bool(re.match('^[a-zA-Z0-9]+$', str1)))

Output

The output of the above example is as shown below −

The given string is
Tutorialspoint123
Checking if the given string is alphanumeric
True

Example 2

In the example given below, we are taking the same program as above but we are taking different input strings 

import re

str1 = "1234@#$"
print("The given string is")
print(str1)

print("Checking if the given string is alphanumeric")
print(bool(re.match('^[a-zA-Z0-9]+$', str1)))

Output

The output of the above example is given below −

The given string is
1234@#$
Checking if the given string is alphanumeric
False

Advertisements