与包含点的字符串匹配的模式

时间:2022-09-13 07:48:33

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("(.*\\..*\\..*)\\.*");

我期望1.1.38,但模式匹配失败。如果我改为Pattern.compile(“(。* \\ .. * \\ .. *)\\。*”);

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

//注意我删除了“。”在最后一个*之前

then 1.1.38.XXX fails

然后1.1.38.XXX失败

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

我的目标是在任何传入的字符串中找到(x.x.x)。

Where am I wrong?

我哪里错了?

2 个解决方案

#1


4  

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

#2


2  

Make your .* matches reluctant with ?

让你的。*匹配不愿意?

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

otherwise .* matches the whole String value.

否则。*匹配整个String值。

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

#1


4  

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

#2


2  

Make your .* matches reluctant with ?

让你的。*匹配不愿意?

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

otherwise .* matches the whole String value.

否则。*匹配整个String值。

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