Regex 正则表达式以匹配最多2位小数的值
我只希望在“.”之前有1到5个数字,在“.”之后有0到2个数字 这就是我到目前为止为正则表达式所做的Regex 正则表达式以匹配最多2位小数的值,regex,Regex,我只希望在“.”之前有1到5个数字,在“.”之后有0到2个数字 这就是我到目前为止为正则表达式所做的 ^\d{1,5}\.?\d{0,2}$ 1.00 -- match 11.01 -- match 111.10 -- match 1111.52 -- match 11111.23 -- match .12 -- no match ... want to match 123456 -- match ... don't want to match because can take up to 5
^\d{1,5}\.?\d{0,2}$
1.00 -- match
11.01 -- match
111.10 -- match
1111.52 -- match
11111.23 -- match
.12 -- no match ... want to match
123456 -- match ... don't want to match because can take up to 5 integers before decimal
1234567 -- match ... don't want to match because can take up to 5 integers before decimal
有人能帮忙吗?您需要这个:
^\d{1,5}\.\d{0,2}$
我已经删除了?
,这使点成为可选的
说你想匹配
.12
与你的规范相矛盾-在点之前没有1-5位数字。你是说{0-5}
?有两个不同的问题:
d{0,5}
,而不是d{1,5}
^\(d{0,5}\.\d{0,2})|(d{0,5}\.?)$
0-5位,然后是小数点,然后是0-2位以上的数字
或
0-5位,后跟可选小数点
此格式还将检测该范围内您在测试中未列出的合法数字,例如
12345.
和0.12
我认为您需要在带小数点的数字和不带小数点的数字之间选择:
^\d{1,5}|\d{0,5}\.\d{1,2}$
^(\d{1,5}|\d{0,5}\.\d{1,2})$
编辑:
感谢user1884032指出缺少的括号:
试试这个:
/^\d{0,5}\.\d{0,2}$/
迟做总比不做好:
^([\d]{0,5})(\.[\d]{1,2})?$
两组:
- 一个匹配0到5位数字
- 另一个从1到2位小数,允许
为0.12
.12
简单而完美:)我在python3中实现的最简单的方法是-
import re
p = re.compile(r'^\d{2}.\d{2}')
print(p.findall('12.59, 11.789, 10.6 lords a-leaping'))
输出-
['12.59']
我使用此工具修补正则表达式。就像dreamFor fast online regex测试一样,我建议使用我已经使用了你建议的,并放入了4567891,它仍然说这是一个不应该的匹配。我试过了,我的建议有效。。。如果第五位数字后有一个点,正则表达式只能匹配7位数字。你有没有检查打字错误?加上括号,效果很好^(\d{1,5}|\d{0,5}\.\d{1,2})$
import re
p = re.compile(r'^\d{2}.\d{2}')
print(p.findall('12.59, 11.789, 10.6 lords a-leaping'))