Note: This is a Java-only question (i.e. no Javascript, sed, Perl, etc.)
I need to filter out all the "reluctant" curly braces ({}
) in a long string of text.
(by "reluctant" I mean as in reluctant quantifier).
I have been able to come up with the following r开发者_如何学Cegex which correctly finds and lists all such occurrences:
Pattern pattern = Pattern.compile("(\\{)(.*?)(\\})", Pattern.DOTALL);
Matcher matcher = pattern.matcher(originalString);
while (matcher.find()) {
Log.d("WITHIN_BRACES", matcher.group(2));
}
My problem now is how to replace every found matcher.group(0)
with the corresponding matcher.group(2)
.
Intuitively I tried:
while (matcher.find()) {
String noBraces = matcher.replaceAll(matcher.group(2));
}
But that replaced all found matcher.group(0)
with only the first matcher.group(2)
, which is of course not what I want.
Is there an expression or a method in Java's regex to perform this "corresponding replaceAll" that I need?
ANSWER: Thanks to the tip below, I have been able to come up with 2 fixes that did the trick:
if (matcher.find()) {
String noBraces = matcher.replaceAll("$2");
}
- Fix #1: Use
"$2"
instead ofmatcher.group(2)
- Fix #2: Use
if
instead ofwhile
.
Works now like a charm.
You can use the special backreference syntax:
String noBraces = matcher.replaceAll("$2");
精彩评论