用Java中的特殊字符替换特殊字符

用Java中的特殊字符替换特殊字符

问题描述:

在我的java代码中,如果一个字符串输入有任何特殊字符,那应该在前面加上 \\

In my java code, if a string input has got any of the special characters mentioned, that should get preceded by \\

特殊字符集为 {+, - ,&& | ||,!,(,),{,},[,],^, 〜,*,?,,,\} 。我尝试使用 String.replaceAll(旧的,新的),但令我惊讶的是,它不工作,即使我给旧和新的适当的值。 p>

Special character set is {+, -, &&, ||, !, (, ), {, },[, ], ^, "", ~, *, ?, :, \}. I tried using String.replaceAll(old,new) but to my surprise its not working, even though I am giving proper values for 'old' and 'new'.

if old=":",new="\:"

我将特殊字符放在一个String数组中,在for循环中迭代,检查它是否存在于字符串中,如果是, input.replaceAll(:,\\:)。但它不给我预期的产出。请帮助

I put the special chars in a String array, iterated it in a for loop, checked whether it is present in the string, if yes, input.replaceAll(":","\\:"). But its not giving me the intended output. Please help

String[] arr = { "+", "-", "&&", "||", "!", "(", ")", "{", "}",
                "[", "]", "^", "\"", "~", "*", "?", ":", "\\", "AND", "OR" };

    for (int i = 0; i < arr.length; i++) {
//'search' is my input string

        if (search.contains((String) arr[i])) {

            String oldString = (String) arr[i];

            String newString = new String("\\" + arr[i]);
            search = search.replaceAll(oldString, newString);
            String newSearch = new String(search.replaceAll(arr[i],
                    newString));


        }
    }


一旦你意识到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