我试图得到regex
可以验证a)接受的数字应该在0到20之间,b)这些数字可以有1或2个十进制数。
正则表达式:
^(10|\d)(\.\d{1,2})?$
(10|\d) allows for a single digit or 10
(\.\d{1,2})? possible decimal followed by 1 or 2 digits
这给了我想要的结果,从0到10(http://regexr.com/)。如果我希望它从0到20接受,我不确定需要修改什么。
有效:
0
1
2 or 2.5
20
无效:
21
.1
.0345
这就是我的尝试:
1. ^\d{0,2}$(\.\d{1,2})?$
- Accepts 0 to 99 but no decimal
2. ^([1-9]|20)$
- Accepts 1 to 9 only
答案 0 :(得分:1)
您可以使用此正则表达式:
^(?:1?\d(?:\.\d{1,2})?|20(?:\.0?0?)?)$
(?:1?\d)
- 将匹配0-19
(?:\.\d{1,2})?
- 将允许可选的1或2个十进制数字。20(?:\.0?0?)?
- 将20
与小数点后的可选零匹配。