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



In this article, we focus on how to check if a string is alphanumeric using regular expressions in Python. Regular expressions are very useful for pattern matching and validation. To use them, first import the re library, which is included by default in Python.

The regular expression ^[a-zA-Z0-9]+$ matches strings that contain only letters (both uppercase and lowercase) and numbers. This expression returns True if the string is alphanumeric; otherwise, it returns False.

Using Regular Expressions

By applying the re.match() function with the above pattern, you can check if the entire string contains only alphanumeric characters.

Example: Checking an Alphanumeric String

In the following example, we check if a given string containing only letters and numbers 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)))

The output of this example is:

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

Example: Checking a String with Special Characters

In this example, we check a string that contains special characters to see if it is alphanumeric. The result should be False because the string includes characters other than letters and numbers:

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)))

The output of this example is:

The given string is
1234@#$
Checking if the given string is alphanumeric
False
Updated on: 2025-09-02T13:22:21+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements