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?
The regex \w is equivalent to [A-Za-z0-9_] , matches alphanumeric characters and underscore.
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.
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+$'
Your regex only matches one character. Try this instead:
if re.match('^[a-zA-Z0-9_]+$',playerName):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With