开发者

Regular expression replace but keep part of the string

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜