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

前端 未结 3 1720
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-01 10:15

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         


        
3条回答
  •  情歌与酒
    2021-01-01 10:31

    …check if is alpha-numeric and possibly contains an underscore.

    Do you mean this literally, so that only one underscore is allowed, total? (Not unreasonable for player names; adjacent underscores in particular can be hard for other players to read.) Should "a_b_c" not match?

    If so:

    if playerName and re.match("^[a-zA-Z0-9]*_?[a-zA-Z0-9]*$", playerName):
    

    The new first part of the condition checks for an empty value, which simplifies the regex.

    This places no restrictions on where the underscore can occur, so all of "_a", "a_", and "_" will match. If you instead want to prevent both leading and trailing underscores, which is again reasonable for player names, change to:

    if re.match("^[a-zA-Z0-9]+(?:_[a-zA-Z0-9]+)?$", playerName):
    // this regex doesn't match an empty string, so that check is unneeded
    

提交回复
热议问题