我需要一个只接受的表达式:
- 数字
- 普通字母(无特殊字符)
- -
也不允许有空格。
示例:正则表达式应匹配:
this-is-quite-alright
它不应该匹配
this -is/not,soålright
我需要一个只接受的表达式:
也不允许有空格。
示例:正则表达式应匹配:
this-is-quite-alright
它不应该匹配
this -is/not,soålright
您可以使用:
^[A-Za-z0-9-]*$
这匹配字符串,可能为空,完全由大写/小写字母 (ASCII AZ)、数字 (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
解释:
^并且$分别是字符串锚的开始和结束
[...]是一个字符类
a-z, A-Z,0-9在字符类中定义范围-作为类中的最后一个字符是文字破折号*是零次或多次重复规范尚不清楚,但如果-仅用于分隔“单词”,即没有双破折号、没有尾随破折号、没有前破折号,那么模式会更复杂(只是稍微!)
_"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
This is a community wiki, an attempt to compile links to related questions about this "URL/SEO slugging" topic. Community is invited to contribute.
-this--is---a-test-- becomes this-is-a-testspam123-spam-eggs-eggs1 reject eggs1-, -spam123, spam--spam[A-z0-9-]+
但是您的问题令人困惑,因为它要求输入字母和数字,并且有一个包含破折号的示例。