Reputation: 6609
I am trying to validate decimal number of 13 digit before and 4 digit after dot excluding comma , i.e comma shouldn't be counted as a digit.
Valid Cases
1,234,567,890,123.1234
1234567890123.1234
123456789012.1234
1234567890123.123
12345.123
1.2
0
In Valid Cases
12345abc.23 // string or special characters not allowed
1,234,567,890,1231.1234
1,234,567,890,123.12341
12345678901231.1234
1234567890123.12341
Current Regex
^[0-9]{1,13}(\.[0-9]{0,4})?$
The current Regex
is counting comma as a digit.
Any help would be great.
Upvotes: 1
Views: 490
Reputation: 163237
You could use a negative lookahead to assert what is directly on the right is not 14 times a digit before matching a dot:
^(?!(?:[^.\s\d]*\d){14})-?\d+(?:,\d{1,3})*(?:\.\d{1,4})?$
Explanation
^
Start of string-?
Optional hyphen(?!
Negative lookahead, assert what follows is not
(?:[^.\s\d]*\d){14}
Match not a digit, whitespace char or dot 14 times)
Close lookahead\d+
Match 1+ digits(?:,\d{1,3})*
Match comma, 1-3 digits and repeat 0+ times (Or use \d+
)(?:\.\d{1,3})?
Optional part, match a dot and 1-4 digits$
End of the stringUpvotes: 1
Reputation: 118
You could just specify the optional count of , Like
^[0-9]{0,1}([,])?[0-9]{0,3}([,])?[0-9]{0,3}([,])?[0-9]{1,3}(\.[0-9]{0,3})?$
Upvotes: 0