【问题标题】:Solving a Regex for a number range解决数字范围的正则表达式
【发布时间】:2012-05-28 04:53:38
【问题描述】:

我需要一个用于验证框架的正则表达式,该框架接受正则表达式格式进行验证。 我不能使用算术和比较运算符。我想出了一个解决方案,但它没有按预期工作。 我想知道我想出的正则表达式有什么问题以及如何正确解决它

1042940999 的任何数字的正则表达式

我的解决方案:

^1042[9-9]|104[3-9][0-9]|10[5-9][0-9][0-9]|1[1-9][0-9][0-9][0-9][0-9]|[2-3][0-9][0-9][0-9][0-9]|40[0-9][0-9][0-9]

但是这个不行。

【问题讨论】:

  • 1024[9-9] 可能只是 10429

标签: regex


【解决方案1】:

试试这个

^(10429|104[3-9][0-9]|10[5-9][0-9]{2}|1[1-9][0-9]{3}|[23][0-9]{4}|40[0-9]{3})$

要生成模式编号范围,请访问here


希望这会有所帮助。

【讨论】:

  • 通过蛮力确认在python中工作:r = re.compile(r'^(10429|104[3-9][0-9]|10[5-9][0-9]{2}|1[1-9][0-9]{3}|[23][0-9]{4}|40[0-9]{3})$')assert all(r.match(str(n)) if n>=10429 and n<=40999 else True for n in range(100000))
  • @om39a:谢谢!去看看 www.regexbuddy.com。这是学习、测试和创建正则表达式的最强大的工具。
【解决方案2】:
  1. 1[1-9][0-9][0-9][0-9][0-9] - 数字太多。
  2. ^1|2|3 实际上意味着 (?:^1)|2|3 - 你需要 ^(?:10429|...|40[0-9][0-9][0-9])$

【讨论】:

  • @om39a: ... 是懒惰,而不是建议 - 重点是在你的模式周围使用 ^(?: )$。无论哪种方式,Cylian 都提供了一个自动化工具,这很好。
【解决方案3】:

10429|104[3-9][0-9]|10[5-9][0-9]{2}|1[1-9][0-9]{3}|[23][0-9]{4}|40[0-9]{3} 应该可以解决问题。

虽然你为什么需要这个超出了我的范围......

【讨论】:

    【解决方案4】:

    试试这个^(10429|104[3-9]\d|10[5-9]\d{2}|1[1-9]\d{3}|[2-3]\d{4}|40\d{3})$

    【讨论】:

    • 这行不通。这将失败,我输入类似这样的内容 10429999999999999999
    • 这和 Cylian 的一样,而是自己创造。
    【解决方案5】:

    我在这里看到了一些很长的正则表达式。这项任务可以在您的模式中没有大量冗余的情况下解决。如果您除了正则表达式之外没有其他任何东西可以使用,那么这就是您想要的模式:

    ^(([123][1-9]|[234]0)[0-9]{3}|10([5-9][0-9]{2}|4([3-9][0-9]|29)))$
    

    在这里它被扩展以向您展示它的含义:

     ^                      #The beginning of the line. This ensures 10429 passes, but 9999910429 doesn't.
     (                      
       ([123][1-9]|[234]0)  #This lets the first two digits be anything from 11-40. We'll deal with 10xxx later on.
       [0-9]{3}             #If the first two digits are 11-40, then the last three can be anything from 000-999. 
     |                      
       10                   #Okay, we've covered 11000-40999. Now for 10429-10999.
       (
         [5-9][0-9]{2}      #Now we've covered 10500-10999; on to the 104xx range.
       |
         4                  
         (
            [3-9][0-9]      #Covers 10430-10499.
         |
            29              #Finally, the special case of 10429.
         )
       )                  
     )
     $                      #The end of the line. This ensures 10429 passes, but 104299999 doesn't.
    

    如果数字不是整个输入,而是嵌入在字符串中(例如,您想获取所有数字 从字符串“blah blah 11000 foo 39256 bar 22222”中,将^$ 替换为\b

    查看它在 Regexr 上的工作:http://regexr.com?312p0

    【讨论】:

      【解决方案6】:

      试试这个 - \b(10429|104[3-9][0-9]|10[5-9][0-9]{2}|1[1-9][0-9]{ 3}|[23][0-9]{4}|40[0-9]{3})\b

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多