正则表达式替换但保留字符串的一部分

时间:2022-02-11 21:40:07

So, if I want to replace b[anything here] in a string with f[same thing here] how would I do that? Example: What is a regular expression that would make foobarfoo to foofarfoo, and foobanfoo to foofanfoo?

那么,如果我想用f替换字符串中的b(任何东西)我该怎么做呢?示例:什么正则表达式可以使foobarfoo到foofarfoo,而foobanfoo到foofanfoo?

1 个解决方案

#1


12  

The basic principle here is a "capture group":

这里的基本原则是“捕获组”:

String output = input.replaceAll("foob(..)foo", "foof$1foo");

Put the portion of interest inside parentheses in the regular expression. It can then be referenced by its group number in replacement text, or via the Matcher.group() method.

将感兴趣的部分放在正则表达式的圆括号中。然后可以通过替换文本中的组号或通过Matcher.group()方法引用它。

#1


12  

The basic principle here is a "capture group":

这里的基本原则是“捕获组”:

String output = input.replaceAll("foob(..)foo", "foof$1foo");

Put the portion of interest inside parentheses in the regular expression. It can then be referenced by its group number in replacement text, or via the Matcher.group() method.

将感兴趣的部分放在正则表达式的圆括号中。然后可以通过替换文本中的组号或通过Matcher.group()方法引用它。