Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 957
soumitra chatterjee Avatar asked Sep 11 '11 19:09

soumitra chatterjee


People also ask

How do you replace a dot in a string?

Call the replace() method, passing it a regular expression that matches all dots as the first parameter and the replacement character as the second. The replace method will return a new string with all dot characters replaced.

How do I change a dot underscore in Java?

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


1 Answers

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)

like image 159
Femi Avatar answered Sep 21 '22 17:09

Femi