Thursday, November 1, 2012

Java Code to Replace character '+'


I need to replace the '+' sign in my string with some other string.

Code:

public class ReplaceString
{
            public static void main(String[] args)
            {
                        String st = "+++ My Data contains Plus sign";                       
                        String sData  = st.replaceAll("+", "Hello,");
                        System.out.println(sData);
            }          
}


But while executing it always throws error,

Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0
+
^



Since '+' is a reserved character in regex, you need to escape it.The solution for this is to include the '+' character within square brackets or as \\+.

So the code looks like this:


public class ReplaceString
{
            public static void main(String[] args)
            {
                        String st = "+ My Data contains Plus sign";                       
                        String sData  = st.replaceAll("[+]", "Hello,");
                        System.out.println(sData);
            }          
}


or

public class ReplaceString
{
            public static void main(String[] args)
            {
                        String st = "+ My Data contains Plus sign";                       
                        String sData  = st.replaceAll("\\+", "Hello,");
                        System.out.println(sData);
            }          
}
 



No comments:

Post a Comment

Thanks for visiting my Blog....Ur comments n suggestions are most valuable for me...Thanks