Reputation: 271
I need your help because I have a regular expression to validate what type of floating point is receiving, this is because the decimal separator can arrive as .
or,
I do not have the way to force a single type of separator so so much I want to validate it by a regex
and I have not been able to finish it, I have tried in several ways and I do not manage to obtain the expected result, you can guide me please.
Numbers:
171
,171.00
, 1770
,1,700
, 1,700.00
,1,777,777
, 1,777,777.00
,,1777777.00
Regular phrase
String patternString = "^[0-9]{0,3}+|(\\,[0-9]{0,3})+(\\.[0-9]{0,2})?$
String patternString = "^[0-9]{0,3}|(\\,[0-9]{0,3})(\\.[0-9]{0,2})?$";
String patternString = "^[0-9]+(\\,[0-9]{0,})+(\\.[0-9]{0,})?$ | ^[0-9]+(\\,[0-9]{0,})?$";
String patternString = "^[0-9]+(\\.[0-9]{0,})+(\\,[0-9]{0,})?$";
Expected result:
For this case I am only evaluating where the pattern of the number is #, ## 0.00
, for the other case I would believe that it would only be to invest the,
for the.
Option 1:
1.71
- Ok1.71717171
- Ok171
- Ok171.00
- Ok1770
- Ok1,700
- Ok1,700.00
- Ok1,777,777
- Ok1,777,777.00
- Ok1777777.00
- OkOption 2:
171,00
- Error (False)1,700.00
- Error (False)1,777,777
- Error (False)1,777,777.00
- Error (False)1777777,00
- Error (False)1,00
- Error (False)Upvotes: 1
Views: 223
Reputation: 163277
In your example numbers, you start with 1+ times a digit. What follows is an optional repeated part that matches a comma and 3 times a digit and the numbers end with an optional dot and 2 times a digit or a dot followed by 1+ times a digit.
You might use and alternation:
^\d+(?:(?:,\d{3})*(?:\.\d{1,2})?|\.\d+)$
In Java:
String regex = "^\\d+(?:(?:,\\d{3})*(?:\\.\\d{1,2})?|\\.\\d+)$";
Explanation
^
Start of the string\d+
Match 1+ digits(?:
Non capturing group
(?:,\d{3})*
Repeat 0+ times matching comma and 3 digits(?:\.\d{1,2})?
Optionally match a dot and 2 digits|
Or\.\d+
Match dot and 1+ digits)
Close non capturing group$
End of the stringSee the regex demo
Upvotes: 1