How to adjust the regular expression in Java?

Asked

Viewed 84 times

0

Look at the code:

Pattern pattern = Pattern.compile("^\\d{1,3}(\\.\\d{3})*,\\d{2}$");
Matcher matcher = pattern.matcher(dadosCSV[position4]);

And I took this regular expression already ready, it’s to validate values like this: 1.500,00.

But now I need to validate values like this: 1500,00.

What the regular expression would look like?

I tried that way:

^\\d{1,3}(\\\\d{3})*,\\d{2}$

But it didn’t work.

  • understood what each piece of regex does?

  • @wladyband, did my answer below solve the problem? If anything is missing, just let me know and I’ll update it :-)

1 answer

1

If you just want to validate the format "multiple digits, comma, two digits", just use:

Pattern pattern = Pattern.compile("^\\d+,\\d{2}$");

The quantifier + means "one or more occurrences", so \\d+ is "one or more digits", which is exactly what it has before the comma. (Remembering that in a String Java, each \\ becomes a single character \, therefore the \\d of String corresponds to regex \d, which is the shortcut for digits from 0 to 9).


In your regex you have \\\\d{3}. How are you in a String, each \\ is translated into a single character \. So this String actually corresponds to the regex \\d{3}, which means "the character \, followed by 3 letters d".

And as before we have \\d{1,3} (from 1 to 3 digits), your regex looks for 1 to 3 digits, optionally followed by \ + 3 letters d (can be repeated several times), followed by a comma and 2 digits. Since "1500.00" has 4 digits before the comma, the first chunk is not enough to take all digits up to the comma (and the part that has \ and 3 letters d does not find any correspondence either). So it does not work.

Interestingly, its regex works for values smaller than 1000 (like "10.00", for example), since it has 1 to 3 digits before the comma (and the part in parentheses is optional, as it can be repeated from zero to several times). See here an example of its regex, and see the difference to mine.


This section in parentheses (\\.\\d{3}) was required to validate a point every 3 digits (as explained in detail in your other question). But now that there are no more dots, we can simply check if there are one or more digits before the comma.

If you want, you can adjust the number of digits as needed. Example:

Pattern pattern = Pattern.compile("^\\d{2,10},\\d{2}$");

In the case, {2,10} will accept between 2 and 10 digits before the comma.

Could also be {2,} to accept at least 2 digits, with no maximum limit. Adjust the values according to what you need.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.