Nikhil Nikhil - 1 month ago 7
Java Question

Regex pattern for numbers with dots

I need a regex expression for this

any number then . and again number and .

So this is valid

1.3.164.1.2583.15.46
546.598.856.1.68.268.695.5955565


but

5..........
...56.5656


are not valid

I tried patterns like:

pattern = "[0-9](\\.[0-9]?*)?*";
pattern = "[0-9](\\.[0-9]?*)?$";
pattern = "[^0-9\\.]";


but none of these fulfill my requirement. Please help?

My existing code is

String PATTERN="\\d+(\\.\\d+)*";
@Override
public void insertString(int arg0, String arg1, AttributeSet arg2)
{

if(!arg1.matches(this.PATTERN))
return;

super.insertString(arg0, arg1, arg2);
}

Answer

Something like this should work:

(\\d+\\.?)+

Edit

Yep, not clear from the description if a final . is allowed (assuming an initial one is not).

If not:

(\\d+\\.?)*\\d+ or \\d+(\\.\\d+)* (if that seems more logical)

Test

for (String test : asList("1.3.164.1.2583.15.46",
    "546.598.856.1.68.268.695.5955565", "5..........", "...56.5656"))
    System.out.println(test.matches("\\d+(\\.\\d+)*"));

produces:

true
true
false
false
Comments