如何在匹配器组而不是整个模式上追加替换? [英] How to appendReplacement on a Matcher group instead of the whole pattern?

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

问题描述

我正在使用 while(matcher.find()) 循环遍历模式的所有匹配项.对于它找到的该模式的每个实例或匹配项,我想用一些新文本替换 matcher.group(3).每个文本都会有所不同,因此我使用 matcher.appendReplacement() 来重建带有新更改的原始字符串.但是,appendReplacement() 替换了整个 Pattern 而不仅仅是组.

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?

这是一些示例代码:

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

类似的东西,它只替换某个组,而不是整个 Pattern.

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

更改正则表达式示例以显示并非所有模式都已分组.

推荐答案

假设您的整个模式匹配 "(prefix)(infix)(suffix)",将 3 个部分捕获到组 1,分别为 2 和 3.现在假设您只想替换第 2 组(中缀),保持前缀和后缀保持原样.

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.

然后你要做的是附加什么 group(1) 匹配(未更改),group(2) 的新替换,以及 group(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.

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

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