I'm trying to replace all the special characters in a string with the escaped version.
The special characters for regex are: $ ^ + \ ?
I'm trying to do this so that I can send a string to the function below that is riddled with regex special characters, and get them replaced with the appropriate \ before the special character.
When I try to replace the characters with null (to delete rather than replace) it works great.
But I'd like to keep the characters in there with the \ in front.
public static String formatter(String name){
final String[] specialChar={"\\\\","\\^",
"\\+","\\$
","\\?"}; //\\ Needs to be first.
// StringBuffer sbuff = new StringBuffer(name);
String tmpString = name;
for (String sChar : specialChar) {
String replaceWith = "\\"+sChar;
System.out.println("SChar is:"+sChar);
tmpString = name.replaceAll(sChar,repl
aceWith);
System.out.println("tmpStr
ing is:"+tmpString);
name = tmpString;
}
return tmpString;
}
Start Free Trial