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

时间:2014-03-16 21:47:09

标签: java regex

模式是:

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

字符串是:

    sentVersion = "1.1.38.24.7";

我做:

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

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

  

//注意我删除了“。”在最后一次*

之前

然后1.1.38.XXX失败

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

我哪里错了?

2 个答案:

答案 0 :(得分:5)

问题可能是由于你的正则表达式的贪婪。尝试这种基于否定的正则表达式模式:

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

在线演示:http://regex101.com/r/sJ5rD4

答案 1 :(得分:2)

使用.*

制作?个匹配reluctant
Pattern r = Pattern.compile("(.*?\\..*?\\..*?)\\..*");

否则.*会匹配整个String值。

见这里:http://regex101.com/r/lM2lD5

相关问题