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

JavaStr Replace

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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)

Solution 2 - Java

If you want to replace a simple string and you don't need the abilities of regular expressions, you can just use replace, not replaceAll.

replace replaces each matching substring but does not interpret its argument as a regular expression.

str = xpath.replace(".", "/*/");

Solution 3 - Java

Use Apache Commons Lang:

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

or with standalone JDK:

String a = "\\*\\"; // or: String a = "/*/";
String replacement = Matcher.quoteReplacement(a);
String searchString = Pattern.quote(".");
String str = xpath.replaceAll(searchString, replacement);

Solution 4 - Java

return sentence.replaceAll("\s",".");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionsoumitra chatterjeeView Question on Stackoverflow
Solution 1 - JavaFemiView Answer on Stackoverflow
Solution 2 - JavakhelwoodView Answer on Stackoverflow
Solution 3 - JavapalacsintView Answer on Stackoverflow
Solution 4 - JavaHazari Ram ArshiView Answer on Stackoverflow