且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Java 中用转义前面的特殊字符替换特殊字符

更新时间:2023-12-05 13:12:34

一旦您意识到 replaceAll 需要一个正则表达式,只需将您的字符编码为正则表达式即可.

Once you realise replaceAll takes a regex, it's just a matter of coding your chars as a regex.

试试这个:

String newSearch = search.replaceAll("(?=[]\[+&|!(){}^"~*?:\\-])", "\\");

那个奇怪的正则表达式是一个向前看" - 一个非捕获断言,以下字符匹配某些东西 - 在这种情况下是一个字符类.

That whacky regex is a "look ahead" - a non capturing assertion that the following char match something - in this case a character class.

请注意,除了 ] 之外,您不需要对字符类中的字符进行转义(即使是第一个或最后一个减号也不需要转义).

Notice how you don't need to escape chars in a character class, except a ] (even the minus don't need escaping if first or last).

\\ 是您编写正则表达式文字 的方式(Java 转义一次,正则表达式转义一次)

The \\ is how you code a regex literal (escape once for java, once for regex)


这是对这项工作的测试:


Here's a test of this working:

public static void main(String[] args) {
    String search = "code:xy";
    String newSearch = search.replaceAll("(?=[]\[+&|!(){}^"~*?:\\-])", "\\");
    System.out.println(newSearch);
}

输出:

code:xy