Joseph
Joseph

Reputation: 11

Regex Exceptions

I am trying to come up with a java regex that will match numbers with 2 too 3 decimals and not match any decimal number more than 3.

this is my regex

[0-9]{2}[.][0-9]{3}

It matches 41.51778000 and 18.740

but I only want it to match numbers that have exactly 3 decimal places and not numbers with more than three

Upvotes: 1

Views: 61

Answers (3)

Mena
Mena

Reputation: 48404

You can invoke Matcher#matches or String.matches instead of, say, Matcher#find to match the whole String.

Otherwise, you can prepend ^ and append $ to your pattern, to delimit start and end of input.

Finally, you can surround your pattern with something like \\D, or \\b or \\w to respectively match non-digits, word boundaries or whitespace around it, if you need to invoke find on an input containing more than 1 instance of the pattern.

Upvotes: 1

anubhava
anubhava

Reputation: 784998

You must use word boundary on either side to stop unexpected matches:

\b[0-9]{2}[.][0-9]{2,3}\b

In Java it would be:

\\b\\d{2}\\.\\d{2,3}\\b

Upvotes: 1

Codebender
Codebender

Reputation: 14471

You need to ask the regex to match the end and start as well.

^[0-9]{2}[.][0-9]{3}$

Upvotes: 1

Related Questions