Advertisement

02.04.2008 at 11:06AM PST, ID: 23135805 | Points: 500
[x]
Attachment Details

Replace multiple diff characters in String

Asked by ecuguru in Java 2 Micro-Edition (J2ME), Java Programming Language, New to Java Programming

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

Start Free Trial
 
Loading Advertisement...
 
[+][-]02.04.2008 at 01:01PM PST, ID: 20817931

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 7-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]02.04.2008 at 09:00PM PST, ID: 20820731

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 7-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]08.21.2008 at 12:12PM PDT, ID: 22283287

Experts Exchange has a courteous staff of administrators who help members get the most out of the website by means of administrative comments like this one.

Start your 7-day free trial to view this Administrative Comment or ask the Experts your question.

 
 
Loading Advertisement...
20080716-EE-VQP-32 / EE_QW_2_20070628