How to Replace dot (.) in a string in Java

soumitra chatterjee picture soumitra chatterjee · Sep 11, 2011 · Viewed 114.9k times · Source

I have a String called persons.name

I want to replace the DOT . with /*/ i.e my output will be persons/*/name

I tried this code:

String a="\\*\\";
str=xpath.replaceAll("\\.", a);

I am getting StringIndexOutOfBoundsException.

How do I replace the dot?

Answer

Femi picture Femi · Sep 11, 2011

You need two backslashes before the dot, one to escape the slash so it gets through, and the other to escape the dot so it becomes literal. Forward slashes and asterisk are treated literal.

str=xpath.replaceAll("\\.", "/*/");          //replaces a literal . with /*/

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)