我正在尝试学习正则表达式,并试图为以下内容编写模式:
-
必须以字母开头
-
可以包含字母、数字或下划线。
-
必须在整个字符串中至少包含3个字母。
我已经试过了:
'#^[a-z0-9_]+$#i' // this one just matches the characters I want
这就是我卡住的地方:
'#^[a-z]{1}[a-z0-9_]+$#i' // doesn't work
我读了http://www.regular-expressions.info/reference.html,但还是卡住了
'#^[a-zA-Z]([0-9_]*[a-zA-Z]){2}[a-zA-Z0-9_]*$#'
[a-zA-Z]
检查第一个约束(以字母开头)
([0-9_]*[a-zA-Z]){2}
检查第二个约束(总共必须有3个字母)
[a-zA-Z0-9_]*
释放了先前的限制,只限制使用允许的字符
应该这样做:
#^[a-zA-Z]{1}('w*[a-zA-Z]'w*){2}$#i
解释:
^[a-zA-Z]{1} // 1st character is a letter
('w*[a-zA-Z]'w*){2}$ // The rest of the body contains exactly 2 letters, and 0 or more of any other word characters (letter, number, underscore)
/^(?:[a-z]'w*){3}$/i
此模式将要求完整字符串包含三个重复的字母,后面跟着零个或多个单词字符('w
与[a-zA-Z0-9_]
相同)。第三次重复中的'w
将消耗字符串中所有剩余的单词字符。
代码(演示):
$tests = [
'7hello',
'Fooey',
'Shoo3y',
'Whoa!',
'A1_B2_C3_',
'_ABC',
'UB40',
'omg',
'Hi_',
'Stackoverflow_',
];
foreach ($tests as $test) {
printf(
"%s : %s'n",
$test,
preg_match('/^(?:[a-z]'w*){3}$/i', $test)
? 'pass'
: 'fail'
);
}
输出:7hello : fail
Fooey : pass
Shoo3y : pass
Whoa! : fail
A1_B2_C3_ : pass
_ABC : fail
UB40 : fail
omg : pass
Hi_ : fail
Stackoverflow_ : pass