How to appendReplacement on a Matcher group instead of the whole pattern?

前端 未结 2 1957
情话喂你
情话喂你 2021-02-01 04:52

I am using a while(matcher.find()) to loop through all of the matches of a Pattern. For each instance or match of that pattern it finds, I want to replace ma

2条回答
  •  轮回少年
    2021-02-01 05:45

    Let's say your entire pattern matches "(prefix)(infix)(suffix)", capturing the 3 parts into groups 1, 2 and 3 respectively. Now let's say you want to replace only group 2 (the infix), leaving the prefix and suffix intact the way they were.

    Then what you do is you append what group(1) matched (unaltered), the new replacement for group(2), and what group(3) matched (unaltered), so something like this:

    matcher.appendReplacement(
        buffer,
        matcher.group(1) + processTheGroup(matcher.group(2)) + matcher.group(3)
    );
    

    This will still match and replace the entire pattern, but since groups 1 and 3 are left untouched, effectively only the infix is replaced.

    You should be able to adapt the same basic technique for your particular scenario.

提交回复
热议问题