Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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


        }
    }
like image 479
Cheese Avatar asked Dec 04 '12 05:12

Cheese


People also ask

How do you escape a special character in Java?

Java Special Characters The solution to avoid this problem, is to use the backslash escape character.

How do you escape special characters?

Escape CharactersUse the backslash character to escape a single character or symbol. Only the character immediately following the backslash is escaped. Note: If you use braces to escape an individual character within a word, the character is escaped, but the word is broken into three tokens.

What is replaceAll \\ s in Java?

Java String replaceAll() The Java String class replaceAll() method returns a string replacing all the sequence of characters matching regex and replacement string.


3 Answers

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
like image 179
Bohemian Avatar answered Oct 18 '22 22:10

Bohemian


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]);
    }
}
like image 29
Rohit Jain Avatar answered Oct 18 '22 23:10

Rohit Jain


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

search = search.replace(oldString, newString);

like image 36
Kaliappan Avatar answered Oct 18 '22 22:10

Kaliappan