How do I verify that a string only contains letters, numbers, underscores and dashes?

前端 未结 11 925
小鲜肉
小鲜肉 2020-11-29 18:51

I know how to do this if I iterate through all of the characters in the string but I am looking for a more elegant method.

11条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 18:59

    A regular expression will do the trick with very little code:

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

提交回复
热议问题