>我需要正则表达式,如果字符串包含小于或等于 20 的数字并且只允许使用数字,则返回 true。
假设您匹配的数字是:
- 整数
- 在 [0,20] 范围内
这应该有效:^(([01]?[0-9])|(20))$
.
如果你匹配浮点数,事情会变得有点混乱。理想情况下,检查数字范围应始终通过平台的数字运算符完成。
匹配小于或等于 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
访问此处了解将来的问题。
支持正则表达式的语言。我将假设它使用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
捕获数字,然后将其转换为数字并检查它。
(b[0-9]b|b1[0-9]b|b20b)
为我工作
只有整数,假设非负数,没有前导 0
我曾经发现百分比小于 20,所以它最终是:
(b[0-9]%|b1[0-9]%|b20%)