如何匹配小于或等于100的数字?

cha*_*nti 27 regex perl

我想匹配的数小于或等于100,它可以是内0-100任何东西,但是该正则表达式不应该匹配为一些其大于100如120,130,150,999,等等.

Cyl*_*ian 44

试试这个

\b(0*(?:[1-9][0-9]?|100))\b
Run Code Online (Sandbox Code Playgroud)

说明

"
\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
"
Run Code Online (Sandbox Code Playgroud)

访问(已删除链接)以了解未来的问题.

  • 您提供的链接受限于请求用户名和密码! (4认同)

mus*_*fan 6

这对于正则表达式如何:

^([0-9]|[1-9][0-9]|100)$
Run Code Online (Sandbox Code Playgroud)

这将验证7,82,100的示例,但不会验证07或082.

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


如果你需要满足浮点数,你应该阅读这个,这是一个你可以使用的表达式:

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


May*_*wal 5

我的实用建议。

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

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

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


Nav*_*dav 1

正则表达式为此

perl -le 'for (qw/0 1 19 32.4 100 77 138 342.1/) { print "$_ is ", /^(?:100|\d\d?)$/ ? "valid input" : "invalid input"}'
Run Code Online (Sandbox Code Playgroud)