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.
精彩评论