Slenkra
Slenkra

Reputation: 830

Regex for thousand separated numbers

How can I verify with regex in Java if a number is thousand separated (for example with dot)?

Of course it doesn't have to accept any negative number. I've already Googled all around and so far the best I found was [1-9]?\.[0-9]*. However, it's not perfect. For example it accepts 1.000000000 which is not correct.

How can I verify a positive number with a dot thousand separator? For example the number: 1.024.553 or 100.000

It should accept:

But not:

Upvotes: 0

Views: 4150

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149050

You could use this pattern:

^\d+|\d{1,3}(?:\.\d{3})*$

This will match any simple sequence of digits without thousands separators, or any sequence with . separators between every 3 digits. If you also want to support a comma as a thousands separator, use this:

^\d+|\d{1,3}(?:[,.]\d{3})*$

Of course, to use any of these in Java, you'll need to escape the \ characters:

String pattern = "^\\d+|\\d{1,3}(?:\\.\\d{3})*$";

Update Given your updated specs, I'd recommend this pattern:

^(?:0|[1-9][0-9]{0,2}(?:\.[0-9]{3})*)$

You can test it here: Regex Tester

Upvotes: 3

Related Questions