0

如果字符串包含小于或等于 20 的数字并且只允许使用数字,我需要正则表达式将返回 true。

4

4 回答 4

2

假设您匹配的数字是:

  • 整数
  • 在 [0,20] 范围内

这应该工作:^(([01]?[0-9])|(20))$.

如果你正在匹配浮点数,事情会变得有点混乱。理想情况下,检查数字范围应始终通过平台的数字运算符完成。

于 2012-07-05T05:54:19.197 回答
2

这将匹配小于或等于 20 的整数

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

解释

(?:            # Match the regular expression below
                  # Match either the regular expression below (attempting the next alternative only if this one fails)
      \b             # Assert position at a word boundary
   |              # Or match regular expression number 2 below (the entire group fails if this one fails to match)
      -              # Match the character “-” literally
)
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 and capture its match into backreference number 1
                  # Match either the regular expression below (attempting the next alternative only if this one fails)
      [0-9]          # Match a single character in the range between “0” and “9”
   |              # Or match regular expression number 2 below (attempting the next alternative only if this one fails)
      1              # Match the character “1” literally
      [0-9]          # Match a single character in the range between “0” and “9”
   |              # Or match regular expression number 3 below (the entire group fails if this one fails to match)
      20             # Match the characters “20” literally
)
\b             # Assert position at a word boundary

访问这里以了解未来的问题。

于 2012-07-05T05:57:27.753 回答
1

我不知道支持正则表达式的语言。我将假设它使用 PCRE 的一些变体。

这里的代码是严格验证字符串包含数字。

只有整数,假设非负数,没有前导 0:

^(1?\d|20)$

只有整数,假设非负,允许任意前导 0:

^0*(1?\d|20)$

任何整数,没有前导 0:

^(+?(1?\d|20)|-\d+)$

任何整数,允许任意前导 0:

^(+?0*(1?\d|20)|-\d+)$

如果数字不是任意大,最好使用松散的正则表达式捕获数字\b[+-]?\d+(\.\d*)?\b,然后将其转换为数字并检查它。

于 2012-07-05T05:54:55.200 回答
1

(\b[0-9]\b|\b1[0-9]\b|\b20\b) 为我工作

只有整数,假设非负数,没有前导 0

我曾经找到小于 20 的百分比,所以它最终是:

(\b[0-9]%|\b1[0-9]%|\b20%)

于 2016-12-15T20:06:12.937 回答