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