如果我想在一个字符串中用f[same thing here]替换b[anything here],我该怎么做呢?例如:用什么正则表达式可以将“foobarfoo”变成“foofarfoo”,将“foobanfoo”变成“foofanfoo”?
如果我想在一个字符串中用f[same thing here]替换b[anything here],我该怎么做呢?例如:用什么正则表达式可以将“foobarfoo”变成“foofarfoo”,将“foobanfoo”变成“foofanfoo”?
String output = input.replaceAll("foob(..)foo", "foof$1foo");
在正则表达式中,将感兴趣的部分放在括号内。然后可以通过组号在replacement text,中引用它,或通过Matcher.group()
方法引用。
"(.*)"
。而"(..)"
只会匹配恰好两个字符。 - corsiKa"Hello ab hello ad".replaceAll("a([abcABC])", "b$1");
会得到 "Hello bb hello ad",对吗? - user976005