How to replace dot (.) In string in Java

I have a line called persons.name

I want to replace the DOT . on /*/ ie my output will be persons/*/name

I tried this code:

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

I get a StringIndexOutOfBoundsException exception.

How to replace a point?

+58
java str-replace
Sep 11 '11 at 19:17
source share
2 answers

You need two backslashes before the point, one to avoid the slash so that it passes, and the other to avoid the point so that it becomes literal. Straight slashes and an asterisk are processed literally.

 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)

+102
Sep 11 '11 at 19:20
source share

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); 
+7
Sep 11 '11 at 19:52
source share



All Articles