Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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


        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
759 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...