Regex for username that allows numbers, letters and spaces

后端 未结 3 1498
耶瑟儿~
耶瑟儿~ 2021-01-13 19:45

I\'m looking for some regex code that I can use to check for a valid username.

I would like for the username to have letters (both upper case and lower case), number

3条回答
  •  执笔经年
    2021-01-13 20:20

    You don't have to use a regex for everything. I find that requirements like the "no two consecutive characters" usually make the regexes so ugly that it's better to do that bit with a simple procedural loop.

    I'd just use something like ^[A-Za-z0-9][A-Za-z0-9 \.\-_]*[A-Za-z0-9]$ (or the equivalents like ::alnum:: if your regex engine is more advanced) and then just check every character in a loop to make sure the next character isn't the same.

    By doing it procedurally, you can check all the other rules you're likely to want at some point without resorting to what I call "regex gymnastics", things like:

    • not allowed to contain your first or last name.
    • no more than two consecutive digits.

    and so forth.

提交回复
热议问题