Reputation: 581
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
Upvotes: 1
Views: 3756
Reputation: 16
this solution work also for one digit after dot:
^\d{1,3}(,{1}\d{3})*(\.\d{1,2})?$
good luck.
Upvotes: 0
Reputation: 3955
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:
Upvotes: 3
Reputation: 5850
This is one of possible regexes you are looking for:
^\d{1,3}([ ,]?\d{3})*([.,]\d+)?$
Demo: https://regex101.com/r/T8tcDP/1
Upvotes: 3
Reputation: 86232
My suggestion is:
^[1-9]((\d{0,2}(,\d{3})*(\.(\d{3},)*\d{1,3})?)|(\d*(\.\d+)?))$
A number either has separators for every 3 digits or it hasn’t (no middle forms). It either has a decimal point and at least one digit after it, or it hasn’t. In all cases does it start with a non-zero digit.
Remember that a dot (period, .
) has a special meaning in regex and therefore needs to be escaped to get a literal point.
Upvotes: 0
Reputation:
This would match your numbers there (?:\d+(?:,\d{3})*(?:\.\d{2})?|\.\d{2})
It would also match .00
just incase. If you don't want it to, just remove
the |\.\d{2}
part.
Add your own boundary constructs as needed ^$
or \b
Expanded
(?:
\d+
(?: , \d{3} )*
(?: \. \d{2} )?
| \. \d{2}
)
Upvotes: 0