Regular expression for monetary value

Asked

Viewed 887 times

0

Watch the code in Java:

String valor = 1.500,00;
Pattern pattern = Pattern.compile("\\d+(\\.\\d{1,2})?");
Matcher matcher = pattern.matcher(valor);

if (matcher.find()) {
    System.out.println("Valor validado - OK");
} else {
    System.out.println("Valor incorreto");
}

I need to validate the String valor. I need it to be true, but it seems that regular expression \\d+(\\.\\d{1,2})? is not certain because it is not compatible with the structure 1.500,00. I’ve tried that way too: \\d{2}$, but it doesn’t work.

I need help getting the regular expression right.

1 answer

3


One option is to:

String valor = "1.500,00"; // <-- faltou as aspas no seu código
Pattern pattern = Pattern.compile("\\d{1,3}(\\.\\d{3})*,\\d{2}");
Matcher matcher = pattern.matcher(valor);
if (matcher.find()) {
    System.out.println("Valor validado - OK");
} else {
    System.out.println("Valor incorreto");
}

The regex begins with \\d{1,3}: from 1 to 3 digits.

Then we have (\\.\\d{3})*. Explaining from the inside out:

  • \\. is a point itself (the point has special meaning in regex - corresponds to any character - and for the regex to consider only the character ., it is necessary to escape it with \)
  • \\d{3} is "exactly 3 digits"
  • the quantifier * indicates "zero or more occurrences" than before. In this case, what you have before is the entire "dot plus 3 digits" sequence (grouped in parentheses)

That is, the sequence "point followed by 3 digits" can be repeated several times (so we can have values like "1,500.00", "1,500,000.00", etc), or none (in the case of values less than 1000).

Then we have the comma, followed by two digits.

The result of the above code is "Valor validado - OK".


If you want, you can use:

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

The markers ^ and $ are, respectively, the beginning and end of the string. So I guarantee that it only has what is specified in regex. If I do not use them, regex may consider valid Strings which contains the number in the middle of the text.


Just to explain the regex you tried:

  • \\d+(\\.\\d{1,2})?: this regex is \\d+ (one or more digits - ie, whichever quantity greater than or equal to 1) followed by a dot and 1 or 2 digits (\\d{1,2}), and that last stretch after the point is optional (because of the ? right after the parentheses).
  • \\d{2}$: this regex only checks if the string ends with 2 digits (no matter what you have before)

Browser other questions tagged

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