How do I write a regex function in Python that checks if a user has only letters and numbers?
I only want my usernames to have letters, numbers, and underscores. No oth开发者_开发百科er symbols, spaces, or anything else.
How can I write a regex to check if it's only letters/numbers/underscores?
Basically:
import re
regex = re.compile("^[a-zA-Z0-9_]+$")
if regex.match(some_string):
do_something()
>>> re.match('^\w+$', '4tg25g_3yg')
<_sre.SRE_Match object at 0x7f8093f198b8>
"^[a-zA-Z0-9_]+$"
or
"^[\w_]+$"
Something like this should work
import re
if re.match("^[A-Za-z0-9_]*$", user_string):
# do something here
精彩评论