Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regular expression to check alphanumeric

Im using the below regular expression to check if a string contains alphanumeric or not but I get result = None.

>>> r = re.match('!^[0-9a-zA-Z]+$','_')
>>> print r
None
like image 436
user1050619 Avatar asked Apr 14 '26 13:04

user1050619


1 Answers

The ! doesn't have any special meaning in RegEx, you need to use ^ to negate the match, like this

>>> re.match('^[^0-9a-zA-Z]+$','_')
<_sre.SRE_Match object; span=(0, 1), match='_'>

In Python 2.x,

>>> re.match('^[^0-9a-zA-Z]+$','_')
<_sre.SRE_Match object at 0x7f435e75f238>

Note: this RegEx will give you a match, only if the entire string is full of non-alphanumeric characters.

If you want to check if any of the characters is non-alphanumeric, then you need to use re.search and drop the + and $, like this

>>> re.search('[^0-9a-zA-Z]', '123abcd!')
<_sre.SRE_Match object; span=(7, 8), match='!'>

It means that find any character other than 0-9, a-z and A-Z, anywhere in the string. (re.match will try to match from the beginning of the string. Read more about the differences between re.search and re.match here).

Note: The best solution to this problem is, using str.isalnum, like this

>>> "123abcdABCD".isalnum()
True
>>> "_".isalnum()
False

This will return True only if the entire string is full of alphanumeric characters. But, if you want to see if any of the characters in the string is alphanumeric, then you need to use any function like this

>>> any(char.isalnum() for char in "_!@#%^$()*")
False
>>> any(char.isalnum() for char in "_!@#%^a()*")
True
like image 66
thefourtheye Avatar answered Apr 17 '26 02:04

thefourtheye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!