如何编写正则表达式以仅匹配数字、字母和破折号? [英] How to write regular expression to match only numbers, letters and dashes?

查看:83
本文介绍了如何编写正则表达式以仅匹配数字、字母和破折号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个只接受的表达式:

I need an expression that will only accept:

  • 数字
  • 普通字母(无特殊字符)
  • -

也不允许有空格.

示例:正则表达式应该匹配:
这还不错

Example: The regular expression should match:
this-is-quite-alright

它不应该匹配
this -is/not,soålright

推荐答案

您可以使用:

^[A-Za-z0-9-]*$

这匹配完全由大写/小写字母 (ASCII A-Z)、数字 (ASCII 0-9) 和破折号组成的字符串,可能为空.

This matches strings, possibly empty, that is wholly composed of uppercase/lowercase letters (ASCII A-Z), digits (ASCII 0-9), and a dash.

这匹配(如在 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
      • If you're looking for matches within a string, then you don't need the anchors
      • a-z, A-Z, 0-9 在一个字符类中定义范围
      • - 作为类中的最后一个字符是文字​​破折号
      • a-z, A-Z, 0-9 in a character class define ranges
      • - as a last character in a class is a literal dash

      规范不清楚,但如果 - 仅用于分隔单词",即没有双破折号,没有尾随破折号,没有前面的破折号,则模式更复杂(只是一点点!)

      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!)

        _"alpha"_    separating dash
       /         \  /
      ^[A-Za-z0-9]+(-[A-Za-z0-9]+)*$
       \__________/| \__________/|\
          "word"   |    "word"   | zero-or-more
                   \_____________/
                    group together
      

      这匹配至少有一个单词"的字符串,其中单词由一个或多个alpha"组成,其中alpha"由字母和数字组成.更多的词"可以跟在后面,它们总是用破折号隔开.

      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.

      这匹配(如在 rubular.com 上看到的):

      this-is-quite-alright
      and-a-1-and-a-2-and-3-4-5
      

      并拒绝:

      --no-way
      no-way--
      no--way
      

      这篇关于如何编写正则表达式以仅匹配数字、字母和破折号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆