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]+$

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.

Was this post helpful?

Leave a Reply

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