April 16, 2012
regex to allow decimals, but no commas
Question by Rookieatthis
I need a regex expression that allows decimals but no commas. Such as:
1200.00
or
50.00
or
40
or
1
The expression is used in a validation to make sure people put in a price as a number, but no commas. I currently have a regex that allows for commas, numbers, and decimals, but I cannot seem to get the commas out.
This is the current regex that I have which doesnt allow commas or decimals, but I want decimals in there
/^[0-9 ]+$/,
Thanks for your help.
Answer by npinti
Something like this should work: ^d+(.d{2})?$
This basically states the following:
^d+
: Start from the beginning of the string (^
) and match one or more digits (d+
).(.d{2})?
: Match a period character (.
) followed by exactly 2 digits (d{2}
). The question mark denotes that the value within the brackets can either exist or not, meaning that it will match either 1 or 0 instances of the pattern.$
: The string must end here.