【问题标题】:Regex for repeating series of numbers and number ranges (e.g. 3 digit numbers and 3 digit number ranges)用于重复数字序列和数字范围的正则表达式(例如 3 位数字和 3 位数字范围)
【发布时间】:2021-05-04 16:44:05
【问题描述】:

我正在寻找一个正则表达式来匹配重复的数字序列。数字/范围本身可以是任何三位数字,例如我要匹配

345
346-348
234,235,236,237-239
234, 235, 236, 237-239
234,234, 236 and 237-239
234,234, 236 or 237-239

我不想匹配

3454
111-222-333
454,4567 (match only 454)

号码可以是任意三位数字。我尝试了不同的正则表达式与 \d{3} 混合,但我没有找到任何有效的方法。感谢您对此的任何帮助。

【问题讨论】:

  • 我很困惑,345 怎么是一个重复的数字序列?
  • 我已经阅读了几次,但无法确定标准是什么。您的意思是要匹配文字字符序列“346-348”还是要匹配“346”、“347”和“348”中的任何一个?为什么需要“345”而不需要“3454”?你能更明确地定义“重复数列”吗?
  • 我正在寻找匹配任何三位数字和三位数字范围
  • 因此您不希望匹配文字字符序列“234、235、236、237-239”,但您希望匹配“234”、“235”、“236”、和/或“237-239”?如果是这样,那么我要求您编辑您的问题,以简单地说您想要匹配三位数字和三位数字范围(技术上:数字的封闭间隔,使用连字符作为绑定分隔符)。在我看来,“重复数字序列”这个词不适合这里。
  • @Bob76:111-222-333 也是有效匹配吗?

标签: regex regex-group regex-greedy


【解决方案1】:

你可以使用这个正则表达式:

^\d{3}(?:-\d{3})?(?:\s*(?:,|and|or)\s*\d{3}(?:-\d{3})?)*(?=,|$)

RegEx Demo

正则表达式详细信息:

  • ^:开始
  • \d{3}:匹配 3 位数字
  • (?:-\d{3})?:可选地后跟一个连字符和 3 位数字
  • (?:: 启动非捕获组
    • \s*:匹配 0 个或多个空格
    • (?:,|and|or):匹配逗号或andor
    • \s*: 匹配 0 个或多个空格
    • \d{3}:匹配 3 位数字
    • (?:-\d{3})?:可选地后跟一个连字符和 3 位数字
  • )*:启动非捕获组。重复此组 0 次或多次
  • (?=,|$):前瞻断言我们在当前位置前面有一个逗号或行尾

【讨论】:

  • 适用于第一组值;但是,它与 454,4567 中的 454 不匹配(仅匹配 454)。有什么想法吗?
【解决方案2】:

对于您显示的示例,您能否尝试以下操作。

^\d{3}(?:-\d{3}$|(?:(?:,\s*\d{3}\s*){1,3}-\d{3})|(?:,\d{3},\s*\d{3}\s*(?:and|or)\s*\d{3}-\d{3})?)*(?=,|$)

Online demo for above regex

说明:为上述添加详细说明。

^\d{3}                   ##Checking from starting of value if value starts from 3 digits.
(?:                      ##Creating 1st capturing group here.
  -\d{3}$|               ##Matching - followed by 3 digits at end of value OR.
  (?:                    ##Creating 2nd capturing group here.
     (?:,\s*\d{3}\s*){1,3} ##In a non-capturing group matching ,\s* followed by 3 digits with \s* and this whole group 3 times.
     -\d{3}              ##Followed by - 3 digits.
  )|                     ##Closing 2nd capturing group OR.
  (?:                    ##Creating 3rd capturing group here.
     ,\d{3},\s*\d{3}\s*  ##Matching , 3 digits, \s* 3 digits \s*
     (?:and|or)          ##Matching and OR or strings in a non-capturing group here.
     \s*\d{3}-\d{3}      ##Matching \s* followed by 3 digits-3digits
  )?                     ##Closing 3rd capturing group keeping it optional.
)                        ##Closing 1st capturing group here.
*(?=,|$)                 ##nd matching its 0 or more matches followed by comma OR end of line.

【讨论】:

  • 111-222-333 这样的样本现在在正则表达式中得到处理,这些值不会被捕获。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-29
  • 2016-04-07
  • 1970-01-01
  • 2013-07-30
相关资源
最近更新 更多