带有或不带有逗号正则表达式的十进制 [英] Decimal with or without commas regular expression
问题描述
我正在尝试编写一个允许带或不带逗号的小数的正则表达式.
I am trying to write a regular expression that allows decimals with or without commas.
我有-
^[0-9]*((,\d{3})?(,\d{3})?(,\d{3})?)*(\.[0-9]{1,10})?$
似乎可以在reg ex tester中使用,但是当我将其放入代码中时,它将无法使用.如果失败的次数是1,000.00,但不是1,000
which seems to work in reg ex tester, but when I put it in my code it doesn't work. If fails for 1,000.00, but not 1,000
我需要它接受1,1000,1000.00,1,000,000.123,1223.456,1,000,123.928等.
I need it to accept 1, 1000, 1000.00, 1,000,000.123, 1223.456, 1,000,123.928 etc.
推荐答案
此正则表达式似乎有效(尝试在此处 ),但稍微复杂一些,同时允许不一致使用,
(即12345,789,000.123).这应该可以解决该问题:
This regex seems to work (try it here), but it is slightly overcomplicated, while at the same time allowing inconsistent use of ,
(i.e 12345,789,000.123). This should solve that problem:
^\d{1,3}(?:(,?)\d{3}(?:\1\d{3})*)?(?:\.\d{1,10})?$
通过使用向后引用(\1
),可以确保始终使用,
或不使用,
.
By using a backreference (\1
) you can make sure that the ,
is either always used, or never.
也可以在.
可选字符前面加上数字,同时仍然要求在,
前面加上数字,但是稍微复杂一些:
Making digits in front of the .
optional while still requiring them in front of a ,
is also possible, but slightly more complicated:
^(?:\d{1,3}(?:(,?)\d{3})?)?(?:\1\d{3})*(\.\d{1,10})?$
这篇关于带有或不带有逗号正则表达式的十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!