Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Regular expression to match alpha-numeric not working?

Tags:

python

regex

I am looking to match a string that is inputted from a website to check if is alpha-numeric and possibly contains an underscore. My code:

if re.match('[a-zA-Z0-9_]',playerName):             # do stuff 

For some reason, this matches with crazy chars for example: nIg○▲ ☆ ★ ◇ ◆

I only want regular A-Z and 0-9 and _ matching, is there something i am missing here?

like image 368
Tommo Avatar asked Jan 18 '11 10:01

Tommo


People also ask

How do you represent alphanumeric in regular expression?

The regex \w is equivalent to [A-Za-z0-9_] , matches alphanumeric characters and underscore.

What does \+ mean in regex?

Example: "a\+" matches "a+" and not a series of one or "a"s. ^ the caret is the anchor for the start of the string, or the negation symbol. Example: "^a" matches "a" at the start of the string. Example: "[^0-9]" matches any non digit.


2 Answers

Python has a special sequence \w for matching alphanumeric and underscore when the LOCALE and UNICODE flags are not specified. So you can modify your pattern as,

pattern = '^\w+$'

like image 155
Rozuur Avatar answered Oct 07 '22 03:10

Rozuur


Your regex only matches one character. Try this instead:

if re.match('^[a-zA-Z0-9_]+$',playerName):  
like image 25
Klaus Byskov Pedersen Avatar answered Oct 07 '22 03:10

Klaus Byskov Pedersen