开发者

Regular expression replace but keep part of the string

开发者 https://www.devze.com 2023-04-10 08:52 出处:网络
So, if I want to replace b[anything here] in a string with f[same thing here] how wou开发者_开发百科ld I do that? Example:

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

精彩评论

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