[英]Iterate Matcher Regex Java
我想給定一個輸入String,對該String的每個包含模式的子字符串進行迭代,然后將另一個模式應用於這些子字符串,並以某種方式替換該部分。 這是代碼:
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(..)
也可以簡化
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.