如何编写正则表达式来仅匹配数字、字母和破折号?
的表达式
- 我需要一个仅接受数字
- 、普通字母(无特殊字符)
- -
也不允许使用空格。
例子: 正则表达式应匹配:this-is-quite-alright
它不应该匹配这个-是/不是,所以正确
I need an expression that will only accept:
- numbers
- normal letters (no special characters)
- -
Spaces are not allowed either.
Example:
The regular expression should match:this-is-quite-alright
It should not matchthis -is/not,soålright
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用:
它匹配完全由大写/小写字母 (ASCII AZ)、数字 (ASCII 0-9) 和破折号组成的字符串(可能为空)。
匹配(如 rubular.com 上所示):
并拒绝:
解释:
^< /code> 和- 如果您要在字符串中查找匹配项,则不需要锚点
$
分别是字符串锚点的开头和结尾[...]
是一个字符类字符类中的
az
、AZ
、0-9
定义范围-
作为类中的最后一个字符是文字破折号*
是零或多次重复regular-expressions.info
变体
规范不清楚,但如果
-
只是用来分隔“words”,即没有双破折号,没有尾部破折号,没有前面的破折号,那么模式更复杂(只是稍微复杂一点!)这匹配至少一个“单词”的字符串,其中单词由一个或多个“alpha”组成,其中“alpha”由字母和数字组成。后面可以有更多“单词”,并且它们总是用破折号分隔。
这匹配(如 rubular.com 上所示):
并拒绝:
You can use:
This matches strings, possibly empty, that is wholly composed of uppercase/lowercase letters (ASCII A-Z), digits (ASCII 0-9), and a dash.
This matches (as seen on rubular.com):
And rejects:
Explanation:
^
and$
are beginning and end of string anchors respectively[...]
is a character classa-z
,A-Z
,0-9
in a character class define ranges-
as a last character in a class is a literal dash*
is zero-or-more repetitionregular-expressions.info
Variation
The specification was not clear, but if
-
is only to be used to separate "words", i.e. no double dash, no trailing dash, no preceding dash, then the pattern is more complex (only slightly!)This matches strings that is at least one "word", where words consists of one or more "alpha", where "alpha" consists of letters and numbers. More "words" can follow, and they're always separated by a dash.
This matches (as seen on rubular.com):
And rejects:
但你的问题很令人困惑,因为它要求输入字母和数字,并且有一个包含破折号的示例。
But your question is confusing as it asks for letters and numbers and has an example containing a dash.
这是一个社区 wiki,尝试编译有关此“URL/SEO slugging”主题的相关问题的链接。邀请社区做出贡献。
相关问题
-this--is---a-test--
变为this-is-a-test
spam123-spam-eggs-eggs1
拒绝eggs1-
、-spam123
、spam--spam
相关标签
[slug]
This is a community wiki, an attempt to compile links to related questions about this "URL/SEO slugging" topic. Community is invited to contribute.
Related questions
-this--is---a-test--
becomesthis-is-a-test
spam123-spam-eggs-eggs1
rejecteggs1-
,-spam123
,spam--spam
Related tags
[slug]