Python Regex for alphanumeric characters

In this post, we will see regex which can be used to check alphanumeric characters.

Let’s say you want to check user’s input and it should contain only characters from a-z, A-Zor 0-9.
Here is the regex to check alphanumeric characters in python.

^[a-zA-Z0-9]*$

Here is the explaination of above regex.

^ : denotes start of string
[ : beginning of character group
a-z : any lowercase letter
A-Z : any uppercase letter
0-9 : any digit
_ : underscore
]: end of character group
* : zero or more of the given characters
$ : denotes end of string

If you do not want to allow empty string, you can use + instead of *.

^[a-zA-Z0-9]+$
import re
def isAlphaNumericStr(text):
   if(re.match("^[a-zA-Z0-9]*$", text) != None):
     return True
   return False
if(isAlphaNumericStr("Java2blog") == True):
   print("Java2blog is a alphanumeric string")
else:
   print("Java2blog is not a alphanumeric string")

if(isAlphaNumericStr("Java$2_blog") == True):
   print("Java$2_blog is a alphanumeric string")
else:
   print("Java$2_blog is not a alphanumeric string")

Output

Java2blog is a alphanumeric string
Java$2_blog is not a alphanumeric string

Here, we need to import re module and use re.matches() method to check alphanumeric characters.

You can use another regex for checking alphanumeric characters and underscore.

^\w+$

Python has a special sequence \w for matching alphanumeric and underscore. Please note that this regex will return true in case if string has alphanumeric and underscore.
For example:
This regex will return true for java2blog_
That’s all about Python Regex to alphanumeric characters.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.