uTubeFan
uTubeFan

Reputation: 6794

Strip all reluctant curly braces using regex

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 regex 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");           
}
  1. Fix #1: Use "$2" instead of matcher.group(2)
  2. Fix #2: Use if instead of while.

Works now like a charm.

Upvotes: 2

Views: 1909

Answers (1)

Kilian Foth
Kilian Foth

Reputation: 14336

You can use the special backreference syntax:

String noBraces = matcher.replaceAll("$2");

Upvotes: 2

Related Questions