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


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?

1/18/2011 10:31:13 AM

Accepted Answer

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

1/18/2011 10:46:21 AM

Your regex only matches one character. Try this instead:

if re.match('^[a-zA-Z0-9_]+$',playerName): 

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow