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?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ysnkyCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
cmalakarCommented:
U can use this..

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

Which replaces ^\$?+ special characters...
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.