English 中文(简体)
如何在Matcher组而不是整个模式上追加Replacement?
原标题:How to appendReplacement on a Matcher group instead of the whole pattern?

我使用while(matcher.find())循环遍历一个Pattern的所有匹配。对于它找到的每个实例或该模式的匹配,我想用一些新的文本替换matcher.group(3)。每个字符串的文本都不一样,所以我使用matcher.appendReplacement()来重建原始字符串,并在其执行过程中进行新的更改。但是,appendReplacement()将替换整个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));
}

但我想做这样的事情(显然这行不通)。

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

类似的东西,它只替换某个组,而不是整个模式。

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

最佳回答

假设您的整个模式匹配“(前缀)(中缀)(后缀)”,将3个部分分别捕获到组1、组2和组3中。现在假设您只想替换组2(中缀),使前缀和后缀保持原样。

然后你要做的是附加什么<code>组(1)</code>匹配(未更改),新的<code>的替换组(2)</code>,以及什么<code<组(3)</coder>匹配(已更改),所以如下所示:

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

这仍然会匹配并替换整个模式,但由于第1组和第3组未受影响,因此实际上只有内野被替换。

您应该能够将相同的基本技术应用于您的特定场景。

问题回答

我看到这已经有了一个公认的答案,但它并不是完全正确的。正确的答案似乎是这样的:

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

这也说明了“$”是.appendReplacement中的一个特殊字符。因此,您必须在“process()”函数中将所有“$”替换为“$”。Matcher.quoteReplacement(replacementString)将为您完成此操作(感谢@Med)

如果第1组或第3组恰好包含“$”,则先前接受的答案将失败。您将得到“java.lang.IllegalArgumentException:非法的组引用”





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签