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

前端 未结 11 923
小鲜肉
小鲜肉 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 19:09

    Regular expression can be very flexible.

    import re;
    re.fullmatch("^[\w-]+$", target_string) # fullmatch looks also workable for python 3.4
    

    \w: Only [a-zA-Z0-9_]

    So you need to add - char for justify hyphen char.

    +: Match one or more repetitions of the preceding char. I guess you don't accept blank input. But if you do, change to * .

    ^: Matches the start of the string.

    $: Matches the end of the string.

    You need these two special characters since you need to avoid the following case. The unwanted chars like & here might appear between the matched pattern.

    &&&PATTERN&&PATTERN

提交回复
热议问题