Link to home
Start Free TrialLog in
Avatar of ecuguru
ecuguru

asked on

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

ASKER CERTIFIED SOLUTION
Avatar of ysnky
ysnky
Flag of Türkiye image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial