Matching patterns to a string containing dots

Sample:

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

Line:

    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 pattern matching fails. If i switch toPattern.compile("(.*\\..*\\..*)\\.*");

// note that I am deleting the ".". until the last *

then 1.1.38.XXXfails

My goal is to find (xxx) in any input line.

Where am I mistaken?

+4
source share
2 answers

The problem is probably due to the greed of your regular expression. Try the negation-based regex pattern:

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

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

+4
source

Make your .*mapping reluctant with?

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

.* String.

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

+2

Source: https://habr.com/ru/post/1532055/


All Articles