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

ぐ巨炮叔叔 提交于 2019-12-02 19:14:06

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.

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"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!