Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching with string containing dots

Tags:

java

regex

Pattern is:

private static Pattern r = Pattern.compile("(.*\\..*\\..*)\\..*");

String is:

    sentVersion = "1.1.38.24.7";

I do:

    Matcher m = r.matcher(sentVersion);
    if (m.find()) {
        guessedClientVersion = m.group(1);
    }

I expect 1.1.38 but the pattern match fails. If I change to Pattern.compile("(.*\\..*\\..*)\\.*");

// notice I remove the "." before the last *

then 1.1.38.XXX fails

My goal is to find (x.x.x) in any incoming string.

Where am I wrong?

like image 631
GJain Avatar asked Mar 21 '23 05:03

GJain


1 Answers

Problem is probably due to greedy-ness of your regex. Try this negation based regex pattern:

private static Pattern r = Pattern.compile("([^.]*\\.[^.]*\\.[^.]*)\\..*");

Online Demo: http://regex101.com/r/sJ5rD4

like image 172
anubhava Avatar answered Mar 28 '23 01:03

anubhava