32

我想匹配一个小于或等于 100 的数字,它可以是 0-100 之间的任何数字,但正则表达式不应匹配大于 100 的数字,例如 120、130、150、999 等。

4

7 回答 7

55

尝试这个

\b(0*(?:[1-9][0-9]?|100))\b

解释

"
\b                # Assert position at a word boundary
(                 # Match the regular expression below and capture its match into backreference number 1
   0              # Match the character “0” literally
      *           # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
   (?:            # Match the regular expression below
                  # Match either the regular expression below (attempting the next alternative only if this one fails)
         [1-9]    # Match a single character in the range between “1” and “9”
         [0-9]    # Match a single character in the range between “0” and “9”
            ?     # Between zero and one times, as many times as possible, giving back as needed (greedy)
      |           # Or match regular expression number 2 below (the entire group fails if this one fails to match)
         100      # Match the characters “100” literally
   )
)
\b                # Assert position at a word boundary
"
于 2012-06-13T09:26:57.457 回答
10

正则表达式怎么样:

^([0-9]|[1-9][0-9]|100)$

例如,这将验证 7、82、100,但不会验证 07 或 082。

检查此以获取有关数字范围检查的更多信息(以及包括零前缀在内的变体)


如果你需要处理浮点数,你应该阅读这个,这里有一个你可以使用的表达式:

浮点:^[-+]?([0-9]|[1-9][0-9]|100)*\.?[0-9]+$

于 2012-06-13T09:20:54.277 回答
6

我的实用建议。

就个人而言,我会完全避免编写如此复杂的正则表达式。如果您的号码在不久的将来从 100 变为 200 怎么办。您的正则表达式将不得不进行重大更改,并且可能更难编写。上述所有解决方案都不是自我解释的,您必须在代码中添加注释来补充它。那是一种气味。

可读性很重要。代码是给人类的,而不是给机器的。

为什么不围绕它编写一些代码并保持正则表达式简单易懂。

于 2016-09-19T19:29:11.727 回答
4

如果您需要正则表达式(最终),请使用代码断言:

 /^(.+)$(??{$^N>=0 && $^N<=100 ? '':'^'})/

测试:

my @nums = (-1, 0, 10, 22, 1e10, 1e-10, 99, 101, 1.001e2);

print join ',', grep 
                /^(.+)$(??{$^N>=0 && $^N<=100 ? '':'^'})/,
                @nums

结果:

 0,10,22,1e-010,99

(==>这是了解代码断言的东西)。

于 2012-06-13T13:27:00.283 回答
1

此正则表达式匹配数字 0-100 音调并禁止数字 001:

\b(0|[1-9][0-9]?|100)\b
于 2014-11-18T05:59:47.667 回答
1

正则表达式

perl -le 'for (qw/0 1 19 32.4 100 77 138 342.1/) { print "$_ is ", /^(?:100|\d\d?)$/ ? "valid input" : "invalid input"}'
于 2012-06-13T09:19:23.550 回答
1

这匹配 0 到 100

^0*([0-9]|[1-8][0-9]|9[0-9]|100)$
于 2017-02-06T12:45:09.993 回答