用户名的正则表达式,允许数字、字母和空格 [英] Regex for username that allows numbers, letters and spaces
问题描述
我正在寻找一些可用于检查有效用户名的正则表达式代码.
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), numbers, spaces, underscores, dashes and dots, but the username must start and end with either a letter or number.
理想情况下,也不允许上面列出的任何特殊字符连续重复多次,即它们可以有任意数量的空格/点/破折号/下划线,但必须至少有它们之间有一个数字或字母.
Ideally, it should also not allow for any of the special characters listed above to be repeated more than once in succession, i.e. they can have as many spaces/dots/dashes/underscores as they want, but there must be at least one number or letter between them.
我也很想知道您是否认为这是一个很好的用户名系统?我已经寻找了一些可以做到这一点的正则表达式,但它们似乎都不允许空格,我希望用户名中有一些空格.
I'm also interested to find out if you think this is a good system for a username? I've had a look for some regex that could do this, but none of them seem to allow spaces, and I would like for the usernames to have some spaces in them.
谢谢:)
推荐答案
所以看起来你希望你的用户名有一个单词"部分(字母或数字的序列),中间穿插一些分隔符"部分.
So it looks like you want your username to have a "word" part (sequence of letters or numbers), interspersed with some "separator" part.
>
正则表达式看起来像这样:
The regex will look something like this:
^[a-z0-9]+(?:[ _.-][a-z0-9]+)*$
这是一个分解示意图:
_____sep-word…____
/ \
^[a-z0-9]+(?:[ _.-][a-z0-9]+)*$ i.e. "word ( sep word )*"
|\_______/ \____/\_______/ |
| "word" "sep" "word" |
| |
from beginning of string... till the end of string
所以本质上我们想要匹配诸如word
、word-sep-word
、word-sep-word-sep-word
、等
So essentially we want to match things like word
, word-sep-word
, word-sep-word-sep-word
, etc.
- 不会有连续的
sep
中间没有word
- 第一个和最后一个字符将始终是
word
的一部分(即不是sep
字符)
- There will be no consecutive
sep
without aword
in between - The first and last char will always be part of a
word
(i.e. not asep
char)
请注意,对于 [ _.-]
,-
位于最后,因此它不是范围定义元字符.(?:...)
是所谓的非捕获组.我们需要括号来对重复进行分组(即(…)*
),但由于我们不需要捕获,我们可以使用(?:…)*
相反.
Note that for [ _.-]
, -
is last so that it's not a range definition metacharacter. The (?:…)
is what is called a non-capturing group. We need the brackets for grouping for the repetition (i.e. (…)*
), but since we don't need the capture, we can use (?:…)*
instead.
要允许大写/各种 Unicode 字母等,只需扩展字符类/根据需要使用更多标志.
To allow uppercase/various Unicode letters etc, just expand the character class/use more flags as necessary.
这篇关于用户名的正则表达式,允许数字、字母和空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!