简体   繁体   中英

Replace special character with an escape preceded special character in Java

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

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="\:"

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));


        }
    }

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

Try this:

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).

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);
}

Output:

code\:xy

String#replaceAll takes a regex as first parameter. So, your code will fail if the input in the string is a meta-character like - + .

You should use String#replace .

And also you don't need the last assignment: -

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

As, you are not using it at all. You are in fact assigning the modified string back to search , so it's not required.

Also, rather than using new String(...) , to build your new string. In fact, you just need a single line in your if-statement .

Ok now, after that explanation , you can now use the below for-loop : -

for (int i = 0; i < arr.length; i++) {
    if (search.contains(arr[i])) {
        search = search.replace(arr[i], "\\" + arr[i]);
    }
}

Try to use the below one. Please use replace method instead of ReplaceAll

search = search.replace(oldString, newString);

when I tried the code below it worked

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,(String) ("\\" + newString));



            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM