有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java循环遍历正则表达式匹配项并替换当前匹配项

考虑以下字符串:

He ordered a pizza with anchovies. Unfortunately, it wasn't the thing he wanted. Besides, pizza with mushroom, pepperoni and anchovies is much better than the normal pizza with anchovies.

假设您需要将pizza with (ingredients)更改为pizza with (ingredients) on a thin crust

为此,我设置了一个正则表达式:

(?i:pizza with [a-zA-Z,\s]*?anchovies)

这捕获了三个匹配项。然后,我继续使用以下代码将on a thin crust添加到每个匹配中:

Pattern p = Pattern.compile("(?i:pizza with [a-zA-Z,\s]*?anchovies)");
Matcher m = p.matcher(string);
while(m.find())
{
    string = string.replace(m.group(), m.group() + "on a thin crust.");
}

然后,其输出将为:

He ordered a pizza with anchovies on a thin crust on a thin crust. Unfortunately, it wasn't the thing he wanted. Besides, pizza with mushroom, pepperoni and anchovies is much better than the normal pizza with anchovies on a thin crust on a thin crust.

发生了什么:

第一个匹配pizza with anchovies与最后一个匹配相同。因此,使用String.replace导致第一个和最后一个匹配更改为pizza with anchovies on a thin crust。因为,我们正在循环所有匹配,最后一个匹配仍然会出现,替换函数也会替换第一个匹配(因为第一个匹配和最后一个匹配是相同的)。因此,我们得到了双on a thin crust

问:

有没有办法只在当前匹配中替换正则表达式匹配


共 (0) 个答案