正则表达式替换,但保留字符串的一部分 [英] Regular expression replace but keep part of the string

查看:52
本文介绍了正则表达式替换,但保留字符串的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

那么,如果我想用f [这里相同的东西]替换字符串中的b [这里的任何东西],我该怎么做?例子:可以使foobarfoo变成foofarfoo,而foobanfoo变成foofanfoo的正则表达式是什么?

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?

推荐答案

此处的基本原理是捕获组":

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.

这篇关于正则表达式替换,但保留字符串的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆