我将创建一个regexp来匹配以下内容:
字符串应该只包含小写alpha-数字字符( and ),其中应该允许单个'-‘。例如,“垃圾桶”应该可以,但是“垃圾桶”或“垃圾桶”不应该。
regexp应该是什么样的呢?如果能解释的话,我会很高兴的。
如果到目前为止是这样的话:
/^[0-9a-z]+-+$/
UPDATED TO:
^(?!a-)+0-9a-z+-?$
我不知道的是如何不允许多个-跟随彼此,或不允许字符串以-开头。
发布于 2012-12-17 21:39:58
^([a-z0-9]+(\-[a-z0-9]+)*)$
这也许能起作用。在http://www.regextester.com/上测试它(选择preg方言,因为它是php的preg_*
函数所使用的)
发布于 2012-12-17 21:44:05
你想要^[a-z0-9]+(-[a-z0-9]+)*$
$str=array("trash-bin","TRASH-Bin","232trash-bin","-trash-bin","trash","t--b");
foreach ($str as $val) {
preg_match('/^[a-z0-9]+(-[a-z0-9]+)*$/',$val,$match);
echo $match[0];
}
>>> trash-bin
>>> 123trash-bin
>>> trash
雷加解释:
^ # Match the start of the string
[a-z0-9]+ # Followed by one or more lowercase letter or digit
(- # Followed by an hyphen
[a-z0-9]+ # Followed by one or more lowercase letter or digit
)* # Pattern inside brackets can occur zero or more times
$ # Followed by the end of the string
发布于 2012-12-17 21:46:32
如果您只需要一个hiphen,并且这也应该是在两个或多个字符(全部是小写字母)之间,那么也许您可以取消以下操作:
^[a-z0-9]+-?[a-z0-9]+$
测试它@ http://www.pagecolumn.com/tool/pregtest.htm。
https://stackoverflow.com/questions/13922533
复制相似问题