Replace multiple diff characters in String

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,replaceWith);
              System.out.println("tmpString is:"+tmpString);
                  name = tmpString;
        }
            return tmpString;
      }

ecuguruAsked:
Who is Participating?
 
ysnkyConnect With a Mentor Commented:
do you look for this; :-)
String str = "^+\\$?";
String strNew = str.replaceAll("\\\\", "\\\\\\\\").replaceAll("\\+", "\\\\+").replaceAll("\\^", "\\\\^").replaceAll("\\$", "\\\\\\$").replaceAll("\\?", "\\\\?");
 
System.out.println(str + ", " + strNew);

Open in new window

0
 
cmalakarConnect With a Mentor Commented:
U can use this..

String test = "^$2?3+\\4";
String new = test.replaceAll("([\\Q^$+?\\\\E])", "\\\\$1");

Which replaces ^\$?+ special characters...
0
All Courses

From novice to tech pro — start learning today.