Regular expression replace but keep part of the string

后端 未结 1 1564
滥情空心
滥情空心 2020-12-31 16:48

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 foofarf

相关标签:
1条回答
  • 2020-12-31 17:20

    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 讨论(0)
提交回复
热议问题