Nikhil
Nikhil

Reputation: 2883

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);
}

Upvotes: 6

Views: 11530

Answers (4)

Cary Swoveland
Cary Swoveland

Reputation: 110675

You could match with the following regular expression.

(?<![.\d])\d+(?:\.\d+)+(?![.\d])

Start your engine!

The negative lookarounds are to avoid matching .1.3.164.1 and 1.3.164.1.. Including \d in the lookarounds is to avoid matching 1.3.16 in 1.3.164.1..

Java's regex engine performs the following operations.

(?<![.\d])  : negative lookbehind asserts following character is not
              preceded by a '.' or digit
\d+         : match 1+ digits
(?:\.\d+)   : match '.' then 1+ digits in a non-capture group
+           : match the non-capture group 1+ times
(?![.\d])   : negative lookahead asserts preceding character is not
              followed by a '.' or digit

Upvotes: 0

Muhammad Ashikuzzaman
Muhammad Ashikuzzaman

Reputation: 3143

This one [0-9]+([.][0-9]+)* equivalent to \\d+([.]\\d+)* is valid for

1.3.164.1.2583.15.46 , 546.598.856.1.68.268.695.5955565 and 5465988561682686955955565

And this one [0-9]+([.][0-9]+)+ equivalent to \\d+([.]\\d+)+ is valid for

1.3.164.1.2583.15.46 and 546.598.856.1.68.268.695.5955565 but not for 5465988561682686955955565

Upvotes: 1

Joe Yang
Joe Yang

Reputation: 23

I was thinking recursive regex here, and my pattern is:

pattern = "\\d+.\\d+(?:.\\d+.\\d+)*"

Upvotes: 0

Dmitri
Dmitri

Reputation: 9157

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

Upvotes: 11

Related Questions