I am trying to write a regular expression that allows decimals with or without commas.
I have –
^[0-9]*((,\d{3})?(,\d{3})?(,\d{3})?)*(\.[0-9]{1,10})?$
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
I need it to accept 1, 1000, 1000.00, 1,000,000.123, 1223.456, 1,000,123.928 etc.
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: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: