Joaquin Iurchuk
Joaquin Iurchuk

Reputation: 5617

Check if String ends with two digits after a dot in Regular Expression?

I'm trying to test if a String ends with EXACTLY two digits after a dot in Java using a Regular Expression. How can achieve this?

Something like "500.23" should return true, while "50.3" or "50" should return false.

I tried things like "500.00".matches("/^[0-9]{2}$/") but it returns false.

Upvotes: 0

Views: 7593

Answers (3)

GameDroids
GameDroids

Reputation: 5662

Here is a RegEx that might help you:

^\d+\.\d{2,2}$

it may neither be perfect nor the most efficient, but it should lead you in the right direction.

^ says that the expression should start here
\d looks for any digit
+ says, that the leading \d can appear as often as necessary (1–infinity)
\. means you are expecting a dot(.) at one point
\d{2,2} thats the trick: it says you want 2 and exactly 2 digits (not less not more)
$ tells you that the expression ends there (after the 2 digits)

in Java the \ needs to be escaped so it would be:

^\\d*\\.\\d{2,2}$

Edit
if you don't need digits before the dot (.) or if you really don't care what comes before the dot, then you can replace the first \d+ by a .* as in Bohemians answer. The (non escaped) dot means that the expression can contain any character (not only digets). Then even the leading ^ might no longer be necessary.

 \\.*\\.\\d{2,2}$

Upvotes: 5

Rustam
Rustam

Reputation: 6515

use this regex

 String s="987234.42";
    if(Pattern.matches("^\\d+(\\.\\d{2})$", s)){   // string must start with digit followed by .(dot) then exactly two digit.
    ....
    }

Upvotes: 2

Bohemian
Bohemian

Reputation: 424993

Firstly, forward slashes are no part of regular expressions whatsoever. They are however used by some languages to delimit regular expressions - but not java, so don't use them.

Secondly, in java matches() must match the whole string to return true (so ^ and $ are implied in the regex).

Try this:

if (str.matches(".*\\.\\d\\d"))
    // it ends with dot then 2 digits

Note that in java a bash slash in a regex requires escaping by a further back slash in a string literal.

Upvotes: 1

Related Questions