Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
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. Let's break down this pattern ?
- ^ ? Matches the beginning of the string
- [a-zA-Z0-9] ? Character class that matches any lowercase letter (a-z), uppercase letter (A-Z), or digit (0-9)
- + ? Matches one or more of the preceding characters
- $ ? Matches the end of the string
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. The re.match() function checks if the pattern matches from the beginning of the string.
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 the above code 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 the above code is ?
The given string is 1234@#$ Checking if the given string is alphanumeric False
Example: Checking an Empty String
It's important to note that an empty string will return False because the + quantifier requires at least one character ?
import re
str1 = ""
print("The given string is empty")
print("Checking if the given string is alphanumeric")
print(bool(re.match('^[a-zA-Z0-9]+$', str1)))
The output of the above code is ?
The given string is empty Checking if the given string is alphanumeric False
Conclusion
The regular expression ^[a-zA-Z0-9]+$ with re.match() provides an efficient way to validate alphanumeric strings in Python, returning True only for strings containing letters and digits.
