组匹配正则表达式在Java中失败

时间:2014-04-24 16:39:12

标签: java regex bash sed

为什么此正则表达式模式无法与Java中的组匹配。当我在带有echosed的bash shell中运行相同的示例时,它可以正常工作。

String s = "Match foo and bar and baz";
//Pattern p = Pattern.compile("Match (.*) or (.*) or (.*)"); //was a typo
Pattern p = Pattern.compile("Match (.*) and (.*) and (.*)");
Matcher m = p.matcher(s);
while (m.find()) {
    System.out.println(m.group(1));
}

我希望与foobarbaz匹配。

$ echo "Match foo and bar and baz" | sed 's/Match \(.*\) and \(.*\) and \(.*\)/\1, \2, \3/'
foo, bar, baz

4 个答案:

答案 0 :(得分:1)

这是由于.*的贪婪性质。你可以使用这个正则表达式:

Pattern p = Pattern.compile("Match (\\S+) and (\\S+) and (\\S+)");

此正则表达式使用\\S+,表示匹配1个或多个非空格。

完整代码

Matcher m = p.matcher(s);
while (m.find()) {
    System.out.println(m.group(1) + ", " + m.group(2) + ", " + m.group(3));
}

答案 1 :(得分:1)

您尝试匹配整个String,所以

while (m.find()) {

只会迭代一次。

单个find()将捕获所有组。因此,您可以将它们打印出来

System.out.println(m.group(1) + " " + m.group(2) + m.group(3));

或在for上使用Matcher#groupCount()循环。

答案 2 :(得分:1)

您的正则表达式是正确的,但您需要打印不同的群组不仅是第1个,例如:

while (m.find()) {
    System.out.println(m.group(1));
    System.out.println(m.group(2));
    System.out.println(m.group(3));
}

答案 3 :(得分:0)

这似乎是一个简单的拼写错误(or - > and):

Pattern p = Pattern.compile("Match (.*) and (.*) and (.*)");

<强>更新

替换:

String s = "Match foo and bar and baz";
String replaced = s.replaceAll("Match (.*) and (.*) and (.*)", "$1, $2, $3");
System.out.println(replaced);