我需要验证一个字符串,该字符串可以包含小写字符和破折号,但不是在开头也不是结尾,也不是重复。那么也可以有数字,但不是在开头。
这是它应该如何运作的:
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]$/
答案 0 :(得分:1)
答案 1 :(得分:0)
/^[a-z](_?[a-z0-9])*$/
虚拟虚拟
答案 2 :(得分:0)
怎么样:
^[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
----------------------------------------------------------------------
答案 3 :(得分:0)
我希望这个解决你的问题
/^[a-z0-9]+((\-{0,1})[a-z0-9]+)+$/
编辑:
以下是更合适的
/^[a-z]+[a-z0-9]+((\-{0,1})[a-z0-9]+)+$/