[英]Regular expression for validating a username?
I'm still kinda new to using Regular Expressions, so here's my plight. 我仍然有点使用正则表达式,所以这是我的困境。 I have some rules for acceptable usernames and I'm trying to make an expression for them.
我有一些可接受的用户名规则,我正在尝试为它们制作表达式。
Here they are: 他们来了:
This is as far as I've gotten with it. 就我而言,这就是我的意思。
/^[a-zA-Z]{1}([a-zA-Z0-9]|\s(?!\s)){0,14}[^\s]$/
It works, for the most part, but doesn't match a single character such as "a". 它在很大程度上起作用,但不匹配单个字符,例如“a”。
Can anyone help me out here? 有人可以帮我从这里出去吗? I'm using PCRE in PHP if that makes any difference.
我在PHP中使用PCRE,如果这有任何区别。
Try this: 试试这个:
/^(?=.{1,15}$)[a-zA-Z][a-zA-Z0-9]*(?: [a-zA-Z0-9]+)*$/
The look-ahead assertion (?=.{1,15}$)
checks the length and the rest checks the structure: 先行断言
(?=.{1,15}$)
检查长度,其余检查结构:
[a-zA-Z]
ensures that the first character is an alphabetic character; [a-zA-Z]
确保第一个字符是字母字符; [a-zA-Z0-9]*
allows any number of following alphanumeric characters; [a-zA-Z0-9]*
允许任意数量的以下字母数字字符; (?: [a-zA-Z0-9]+)*
allows any number of sequences of a single space (not \\s
that allows any whitespace character) that must be followed by at least one alphanumeric character (see PCRE subpatterns for the syntax of (?:…)
). (?: [a-zA-Z0-9]+)*
允许任何数量的一个单一的空间的序列(未的\\s
,允许任何空白字符),必须遵循通过至少一个字母数字字符(参见用于PCRE子模式 (?:…)
语法 。 You could also remove the look-ahead assertion and check the length with strlen
. 您还可以删除前瞻断言并使用
strlen
检查长度。
The main problem of your regexp is that it needs at least two characters two have a match : 你的正则表达式的主要问题是它需要至少两个字符两个匹配:
[a-zA-Z]{1}
part [a-zA-Z]{1}
部分 [^\\s]
part [^\\s]
部分 Beside this problem, I see some parts of your regexp that could be improved : 除了这个问题,我看到你的正则表达式的一些部分可以改进:
[^\\s]
class will match any character, except spaces : a dot or semi-colon will be accepted, try to use the [a-zA-Z0-9]
class here to ensure the character is a correct one. [^\\s]
类将匹配任何字符,空格除外:将接受点或分号,尝试使用[a-zA-Z0-9]
类来确保字符是正确的。 {1}
part at the beginning, as the regexp will match exactly one character by default {1}
开头部分,正则表达式将匹配在默认情况下只有一个角色 在你的第一个角色可选后做一切
^[a-zA-Z]?([a-zA-Z0-9]|\s(?!\s)){0,14}[^\s]$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.