user976005
user976005

Reputation:

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 would I do that? Example: What is a regular expression that would make foobarfoo to foofarfoo, and foobanfoo to foofanfoo?

Upvotes: 11

Views: 14706

Answers (1)

erickson
erickson

Reputation: 269647

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.

Upvotes: 16

Related Questions