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

核能气质少年 提交于 2019-11-26 11:19:34

问题


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?


回答1:


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)




回答2:


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);



回答3:


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(".", "/*/");



回答4:


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



来源:https://stackoverflow.com/questions/7380626/how-to-replace-dot-in-a-string-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!