简体   繁体   中英

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 other 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_]+$"

要么

"^[\w_]+$"

Something like this should work

import re
if re.match("^[A-Za-z0-9_]*$", user_string):
    # do something here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM