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