Dinesh Kumar
Dinesh Kumar

Reputation: 3142

Regex for 8,2 decimal with thousand separator in JAVA

I have tried a few regex's of my own but have always had some bug or the other.

My requirement is to get a regex for 8,2 decimal, e.g. 000,000.00

Invalid ones are as follows

Valid ones are as follows

Update: This to check a valid input from user. Fraction part or commas are not mandatory.

Upvotes: 0

Views: 531

Answers (2)

rock321987
rock321987

Reputation: 11032

For at most 8 digits before decimal

I came up with a rather complicated regular expression (assuming the numbers have mandatory ,)

^\d{1,3}((?:(?<=\d),(?=\d{3})\d{3})){0,2}(\.\d{2})?$

Regex Demo

You can add an or condition in above regex for matching non-comma patterns

^(\d{1,3}((?:(?<=\d),(?=\d{3})\d{3})){0,2}|^\d{0,8})(\.\d{2})?$

Java Regex

^(\\d{1,3}((?:(?<=\\d),(?=\\d{3})\\d{3})){0,2}|\\d{0,8})(\\.\\d{2})?$

Ideone Demo

For at most 6 digits before decimal use

^(\d{1,3}((?:(?<=\d),(?=\d{3})\d{3})){0,1}|^\d{0,6})(\.\d{2})?$

Upvotes: 2

Tamas Hegedus
Tamas Hegedus

Reputation: 29926

Try this regex:

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

See in regex101

Upvotes: 1

Related Questions