我需要一个只接受以下内容的表达式:
空格也是不允许的。
例子:
正则表达式应该匹配:
this-is-quite-alright
不应该匹配
this -is/not,soålright
您可以使用:
^[A-Za-z0-9-]*$
这匹配完全由大写/小写字母 (ASCII A-Z)、数字 (ASCII 0-9) 和破折号组成的字符串(可能为空)。
这匹配 (如 rubular.com 上所示):
this-is-quite-alright
and-a-1-and-a-2-and-3-4-5
yep---------this-is-also-okay
并拒绝:
this -is/not,soålright
hello world
解释:
-
^
and $
are beginning and end of string anchors respectively
-
[...]
is a character class
-
a-z
, A-Z
, 0-9
在字符类中定义范围
-
-
作为类中的最后一个字符是字面破折号
-
*
是零次或多次重复
正则表达式.info
变化
规格不清楚,但如果-
仅用于分隔“单词”,即没有双破折号,没有尾部破折号,没有前面的破折号,那么模式更复杂(只是稍微复杂一点!)
_"alpha"_ separating dash
/ \ /
^[A-Za-z0-9]+(-[A-Za-z0-9]+)*$
\__________/| \__________/|\
"word" | "word" | zero-or-more
\_____________/
group together
这会匹配至少包含一个“单词”的字符串,其中单词由一个或多个“alpha”组成,其中“alpha”由字母和数字组成。后面可以有更多“单词”,并且它们总是用破折号分隔。
这匹配 (如 rubular.com 上所示):
this-is-quite-alright
and-a-1-and-a-2-and-3-4-5
并拒绝:
--no-way
no-way--
no--way
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)