[英]How to Replace dot (.) in a string in Java
I have a String called persons.name
我有一个名为
persons.name
的字符串
I want to replace the DOT .
我想更换 DOT
.
with /*/
ie my output will be persons/*/name
使用
/*/
即我的输出将是persons/*/name
I tried this code:我试过这个代码:
String a="\\*\\";
str=xpath.replaceAll("\\.", a);
I am getting StringIndexOutOfBoundsException.我收到 StringIndexOutOfBoundsException。
How do I replace the dot?我如何替换点?
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) http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)
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
,而不是replaceAll
。
replace
replaces each matching substring but does not interpret its argument as a regular expression. replace
替换每个匹配的子字符串,但不将其参数解释为正则表达式。
str = xpath.replace(".", "/*/");
Use Apache Commons Lang :使用Apache Commons Lang :
String a= "\\*\\";
str = StringUtils.replace(xpath, ".", a);
or with standalone JDK:或使用独立的 JDK:
String a = "\\*\\"; // or: String a = "/*/";
String replacement = Matcher.quoteReplacement(a);
String searchString = Pattern.quote(".");
String str = xpath.replaceAll(searchString, replacement);
return sentence.replaceAll("\\s",".");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.