Reputation: 11
How to build a regular expression that allows only int CSV or one/two decimal places CSV
Engine: Chrome HTML regular expression that is included in the tag
1 Pass (since it classfies as one element CSV)
1, Fail (since there is no int or decimal number after comma)
1,2 Pass
1,2,1.0 Pass
3.05,1 Pass
3.005,2 Fail (Since there is three decimal places)
1,A1,3 Fail (Since there is A1 not an int or decimal number in the list)
2,D Fail (Since there is char not int in the CSV)
[blank] Fail (Since blank is not a CSV)
, Fail (Since there has to a int or decimal preceeding and suceeding the comma)
The following doesn't work correctly.
^[\d,\.]+$
Upvotes: 0
Views: 43
Reputation: 15482
You can use the following regex:
^\d(?:\.\d{1,2})?(,\d(?:\.\d{1,2})?)*$
It will match:
^
: start of string\d(?:\.\d{1,2})?
: a digit, optionally followed by a dot and one or two digits(,\d(?:\.\d{1,2})?)*
: optionally followed by a comma and the previous regex part$
: end of stringCheck the regex demo here.
Upvotes: 1