[英]Pattern matcher is not giving expected output
I have the below code. 我有下面的代码。
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++;
}
I am trying to print the string inside two %%%
. 我正在尝试在两个%%%
内打印字符串。 So I am expecting below output: 所以我期望下面的输出:
%%%variable1%%%
variable1
%%%variable2%%%
variable2
But the actual output is: 但是实际输出是:
%%%variable1%%%
variable1
variable2
variable2
Why is it so? 为什么会这样呢? What is the problem with this? 这是什么问题?
You need to remove i
. 您需要删除i
。 There is no need of it 没有必要
while (m.find()) {
System.out.println(m.group());
String variables=m.group().replaceAll("%%%", "");
System.out.println(variables);
}
You don't also need replaceAll
because what you require is already in first capturing group 您也不需要replaceAll
因为您所需要的已经在第一个捕获组中
while (m.find()) {
System.out.println(m.group());
System.out.println(m.group(1));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.