public String replaceAll(
@NotNull String regex,
@NotNull String replacement
)
在 Java 中,replaceAll 是用来进行正则替换的,用法是
字符串.replaceAll(正则表达式, 要替换的值);
如果你只想替换字符串内的所有某个字符串为另一个字符串,使用 String.replace(String, String) 就足够了。
str.replaceAll(regex, replacement)
实际上相当于
Pattern.compile(regex).matcher(str).replaceAll(replacement)
正如 javadoc 中所说
Note that backslashes (
\
) and dollar signs ($
) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string;
在 replacement
你可以用 $
加数字
来代表正则匹配组。
我们可以充分发挥正则特性,快速进行一些不用正则写起来麻烦的替换操作。
比如我需要把 &
加上一个 0123456789ABCDEFabcdef
之中的其中一个字符,替换为 §
加上那个字符,就可以这样子写
// str = "&aThis is a &ntest."
str = str.replaceAll("&([0-9A-Fa-f])", "§$1");
// str = "§aThis is a &ntest."
我发现我在网上搜到的用法和示例好像都没有说到可以使用 $
来代表组的值,算是踩了个坑,于是分享一下。