我需要验证一个字符串,该字符串可以有小写字符和短划线,但不能在开头、结尾或重复。然后也可以有数字,但不能在开头。
这就是它应该如何工作:
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-z'd]|[a-z'd]'-)*[a-z'd]+$
演示说明如下:http://regex101.com/r/mE8pB8
怎么样:
^[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-z](_?[a-z0-9])*$/
伪
我希望这个能解决你的问题
/^[a-z0-9]+(('-{0,1})[a-z0-9]+)+$/
编辑:
以下是更合适的
/^[a-z]+[a-z0-9]+(('-{0,1})[a-z0-9]+)+$/