1000 - valid
1,000 - valid
1,000.00 - valid
1000.00 - valid
1000.00.00 - invalid
1,0.00 - invalid
1,000,00.00 - invalid
1,000,000.12 - valid
no of decimal places can be unlimited
I've been trying to find the right regex pattern, can't seem to find one that will accomodate all validations. Can anyone help
the pattern ^[1-9]\d{0,2}(.\d{3})*(,\d+)?$ did not work for me, based from the similar thread here
You should try this expression:
^\d{1,3}|\d(([ ,]?\d{3})*([.,]\d{2}+)?$)
With this expression is covered with the scenarios raised.
Here the complete example:
public class Decimal {
private static String REGEX = "^\\d{1,3}|\\d(([ ,]?\\d{3})*([.,]\\d{2}+)?$)";
public static void main(String[] args) {
String data[] = {"1000", "1,000", "1,000.00", "1000.00", "1000.00.00", "1,0.00", "1,000,00.00", "1,000,000.12"};
Pattern.compile(REGEX);
for (int i = 0; i < data.length; i++) {
if (data[i].matches(REGEX)) {
System.out.println(data[i] + " - valid");
} else {
System.out.println(data[i] + " - invalid");
}
}
}
}
The output: