开发者

Strip all reluctant curly braces using regex

开发者 https://www.devze.com 2023-04-03 06:07 出处:网络
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.

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

Works now like a charm.


You can use the special backreference syntax:

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号