GJain
GJain

Reputation: 5093

Pattern matching with string containing dots

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?

Upvotes: 4

Views: 1777

Answers (2)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279920

Make your .* matches reluctant with ?

Pattern r = Pattern.compile("(.*?\\..*?\\..*?)\\..*");

otherwise .* matches the whole String value.

See here: http://regex101.com/r/lM2lD5

Upvotes: 2

anubhava
anubhava

Reputation: 785038

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

Upvotes: 5

Related Questions