如何appendReplacement在匹配组,而不是整个格局? [英] How to appendReplacement on a Matcher group instead of the whole pattern?

查看:347
本文介绍了如何appendReplacement在匹配组,而不是整个格局?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是而(matcher.find())来通过全体一个模式的匹配循环。对于找到该模式的每个实例或比赛,我想用一些新的文本替换 matcher.group(3)。该文本将成为每个人,所以我用 matcher.appendReplacement()来重建原始字符串有了新的变化,因为它不用通过不同。然而, appendReplacement()替换整个模式而不仅仅是小组。

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 matcher.group(3) with some new text. This text will be different for each one so I am using matcher.appendReplacement() to rebuild the original string with the new changes as it goes through. However, appendReplacement() replaces the entire Pattern instead of just the group.

我怎样才能做到这一点,但只修改第三组的比赛,而不是整个模式?

How can I do this but only modify the third group of the match rather than the entire Pattern?

下面是一些例子code:

Here is some example code:

Pattern pattern = Pattern.compile("THE (REGEX) (EXPRESSION) (WITH MULTIPLE) GROUPS");
Matcher matcher = pattern.matcher("THE TEXT TO SEARCH AND MODIFY");
StringBuffer buffer = new StringBuffer();

while(matcher.find()){
   matcher.appendReplacement(buffer, processTheGroup(matcher.group(3));
}

但我想这样做(这显然不工作)。

but I would like to do something like this (obviously this doesn't work).

...
while(matcher.find()){
   matcher.group(3).appendReplacement(buffer, processTheGroup(matcher.group(3));
}

类似的东西,它只是取代了某个组,而不是整个模式。

Something like that, where it only replaces a certain group, not the whole Pattern.

编辑:改变了正则表达式的例子来说明,并非所有的格局被分组

推荐答案

比方说,你的整个模式匹配(preFIX)(中缀)(后缀)分别捕获3份成组1,2和3。现在让我们假设你想只更换组2(中缀),留下preFIX和后缀完好他们的方式。

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.

然后你要做的就是追加什么组(1)匹配(不变),为新更换的组(2),什么组(3)匹配(不变),所以是这样的:

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)
);

这仍然将匹配和替换整个格局,但由于组1和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.

这篇关于如何appendReplacement在匹配组,而不是整个格局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆