Reputation:
I would like given a input String, iterate every substring of this String that contain a pattern, then apply to these substrings another pattern, and replace that part in some way. This is the code:
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;
}
The problem is that I cannot get the substring that matches every matcher.find()
. So if I have like input "{{nowrap|x}} {{nowrap|y}}"
I would like to iterate two times and get the substring {{nowrap|x}}
in the first while, and {{nowrap|y}}
in the second.
Thanks in advance.
Upvotes: 1
Views: 3597
Reputation: 109
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;
}
Two small mistakes:
matcher.group(0)
to only use your match not the whole cell in every iteration|
symbol in a regexreplace(..)
can be simpiflied as wellUpvotes: 2