Java 模式匹配器未提供预期的输出

Java 模式匹配器未提供预期的输出,java,regex,Java,Regex,我有下面的代码 String testdata = "%%%variable1%%% is not equal to %%%variable2%%%"; Pattern p = Pattern.compile("\\%%%(.*?)\\%%%"); Matcher m = p.matcher(testdata); String variables = ""; int i = 0; while (m.find()) { System.out.println(m.group());

我有下面的代码

String testdata = "%%%variable1%%% is not equal to %%%variable2%%%";
Pattern p = Pattern.compile("\\%%%(.*?)\\%%%");
Matcher m = p.matcher(testdata);
String variables = "";
int i = 0;
while (m.find()) {
    System.out.println(m.group());
    variables=m.group().replaceAll("%%%", "");
    System.out.println(variables);
    i++;
}
我正在尝试打印两个
%%%%
中的字符串。 因此,我期望以下输出:

%%%variable1%%% 
variable1 
%%%variable2%%% 
variable2
但实际产出是:

%%%variable1%%%
variable1
variable2
variable2

为什么会这样?这有什么问题?

您需要删除
i
。没有必要

while (m.find()) {
      System.out.println(m.group());
      String variables=m.group().replaceAll("%%%", "");
      System.out.println(variables);
}

您也不需要
replaceAll
,因为您需要的已经在第一个捕获组中

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

您需要删除
i
。没有必要

while (m.find()) {
      System.out.println(m.group());
      String variables=m.group().replaceAll("%%%", "");
      System.out.println(variables);
}

您也不需要
replaceAll
,因为您需要的已经在第一个捕获组中

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

如果删除
i++
并使用
组(0)
?@npinti:它起作用了。谢谢。:)如果还有一个变量,就会出现错误。。如果删除
i++
并使用
group(0)
?@npinti:它起作用了。谢谢。:)如果还有一个变量,就会出现错误。。