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.
Here is the explaination of above regex.
^ : denotes start of string[ : beginning of character groupa-z : any lowercase letterA-Z : any uppercase letter0-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 *.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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
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.
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.