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

前端 未结 2 1920
情话喂你
情话喂你 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:32

    I see this already has an accepted answer, but it is not fully correct. The correct answer appears to be something like this:

    .appendReplacement("$1" + process(m.group(2)) + "$3");
    

    This also illustrates that "$" is a special character in .appendReplacement. Therefore you must take care in your "process()" function to replace all "$" with "\$". Matcher.quoteReplacement(replacementString) will do this for you (thanks @Med)

    The previous accepted answer will fail if either groups 1 or 3 happen to contain a "$". You'll end up with "java.lang.IllegalArgumentException: Illegal group reference"

提交回复
热议问题