我想给定一个输入字符串,迭代该字符串中包含模式的每个子字符串,然后将另一个模式应用于这些子字符串,并以某种方式替换该部分。 这是代码:
public static String parseLinkCell1NoLost(String cell) {
String link = cell;
Pattern catPattern = Pattern.compile("\\{\\{(.*?)\\}\\}", Pattern.MULTILINE);
Matcher matcher = catPattern.matcher(cell);
while (matcher.find()) {
Pattern newP = Pattern.compile("\\{\\{nowrap|(.*?)\\}\\}", Pattern.MULTILINE);
Matcher m = newP.matcher(cell);
if (m.matches()) {
String rest = m.group(0);
String prov = m.group(1);
String[] temp = prov.split("\\|");
if (temp == null || temp.length == 0) {
return link;
} else {
link = link.replace(rest, temp[1]);
}
}
}
return link;
}
问题是我无法获取与每个 matcher.find()
匹配的子字符串。因此,如果我有类似的输入 "{{nowrap|x}} {{nowrap|y}}"
我想迭代两次并获取子字符串 {{nowrap|x}}第一个时间为
,第二个时间为 {{nowrap|y}}
。
提前致谢。
最佳答案
public static String parseLinkCell1NoLost(String cell) {
String link = cell;
Pattern catPattern = Pattern.compile("\\{\\{(.*?)\\}\\}", Pattern.MULTILINE);
Matcher matcher = catPattern.matcher(cell);
while (matcher.find()) {
Pattern newP = Pattern.compile("\\{\\{nowrap\\|(.*?)\\}\\}", Pattern.MULTILINE);
Matcher m = newP.matcher(matcher.group(0));
if (m.matches()) {
String rest = m.group(0);
String prov = m.group(1);
link = link.replace(rest, prov);
}
}
return link;
}
两个小错误:
- 在循环中,您应该使用
matcher.group(0)
仅使用您的匹配项,而不是每次迭代中的整个单元格 - 您需要转义正则表达式中的
|
符号 - 一旦纠正,
replace(..)
也可以简化
关于java - 迭代匹配器正则表达式 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40512046/