Gdaimon
Gdaimon

Reputation: 271

Regular expression Decimals (Dynamic) Java

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

 

  1. Option: String patternString = "^[0-9]{0,3}+|(\\,[0-9]{0,3})+(\\.[0-9]{0,2})?$
  2. Option: String patternString = "^[0-9]{0,3}|(\\,[0-9]{0,3})(\\.[0-9]{0,2})?$";
  3. Option: String patternString = "^[0-9]+(\\,[0-9]{0,})+(\\.[0-9]{0,})?$ | ^[0-9]+(\\,[0-9]{0,})?$";
  4. Option: 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:

Option 2:

Upvotes: 1

Views: 223

Answers (1)

The fourth bird
The fourth bird

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 string

See the regex demo

Upvotes: 1

Related Questions