[英]preg-match for repeated characters
我需要验证一个字符串,该字符串可以包含小写字符和短划线,但不能在开头也不是结尾,也不能重复。 然后也可以有数字,但不是在开头。
这是它应该如何工作:
Match: ab9cd-a9bc-abbbc95
Not match: 5abcd
Not match: abbcd-
Not match: -abcd
Not match: abcd--abcd
除了最后一种情况,我已经能够完成所有事情,重复的短划线不应该匹配。
我有这个:
/^[a-z]+[a-z0-9\-]+[a-z0-9]$/
我试过这个,但没有按预期工作:
/^[a-z]+[a-z0-9\-?]+[a-z0-9]$/
/^[a-z](_?[a-z0-9])*$/
假人
怎么样:
^[a-z][a-z0-9]*(?:-?[a-z0-9]+)*[a-z0-9]$
例:
$arr = array('ab9cd-a9bc-abbbc95','5abcd','abbcd-','-abcd','abcd--abcd');
foreach($arr as $str) {
if (preg_match('/^[a-z][a-z0-9]*(?:-?[a-z0-9]+)*[a-z0-9]$/', $str)) {
echo "OK : $str\n";
} else {
echo "KO : $str\n";
}
}
输出:
OK : ab9cd-a9bc-abbbc95
KO : 5abcd
KO : abbcd-
KO : -abcd
KO : abcd--abcd
解释:(来自YAPE :: Regex :: Explain)
The regular expression:
(?-imsx:^[a-z][a-z0-9]*(?:-?[a-z0-9]+)*[a-z0-9]$)
matches as follows:
NODE EXPLANATION
----------------------------------------------------------------------
(?-imsx: group, but do not capture (case-sensitive)
(with ^ and $ matching normally) (with . not
matching \n) (matching whitespace and #
normally):
----------------------------------------------------------------------
^ the beginning of the string
----------------------------------------------------------------------
[a-z] any character of: 'a' to 'z'
----------------------------------------------------------------------
[a-z0-9]* any character of: 'a' to 'z', '0' to '9'
(0 or more times (matching the most amount
possible))
----------------------------------------------------------------------
(?: group, but do not capture (0 or more times
(matching the most amount possible)):
----------------------------------------------------------------------
-? '-' (optional (matching the most amount
possible))
----------------------------------------------------------------------
[a-z0-9]+ any character of: 'a' to 'z', '0' to '9'
(1 or more times (matching the most
amount possible))
----------------------------------------------------------------------
)* end of grouping
----------------------------------------------------------------------
[a-z0-9] any character of: 'a' to 'z', '0' to '9'
----------------------------------------------------------------------
$ before an optional \n, and the end of the
string
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
我希望这个解决你的问题
/^[a-z0-9]+((\-{0,1})[a-z0-9]+)+$/
编辑:
以下更合适
/^[a-z]+[a-z0-9]+((\-{0,1})[a-z0-9]+)+$/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.