简体   繁体   English

字符串函数-replaceAll不适用于“。”

[英]String functions - replaceAll not working for “.”

I was going through replaceAll function. 我正在通过replaceAll函数。 I had following string: 我有以下字符串:

String str = "com.sac.src.abc.def";

I had to replace all dot's with / .So I tried 我必须用/替换所有点。

str.replaceAll(".","/");   

But what I was getting was,that my string converted to - 但是我得到的是,我的字符串转换为-

///////////////////////////////////////////////////////

I don't know what's going wrong. 我不知道怎么了。

. means "any character". 表示“任何字符”。 You need to escape it: 您需要对其进行转义:

"\\."

Instead of replaceAll, use replace method like: 代替replaceAll,使用如下的replace方法:

str.replace(".","/");

"." “。” is a special character in REGEX world and replaceAll takes regex as first input parameter in the method. 是REGEX世界中的特殊字符,而replaceAll将regex作为方法中的第一个输入参数。 Since you are not using regex already, use replace method. 由于您尚未使用正则表达式,请使用replace方法。

. is a special character which matches any single character . 与任何单个字符匹配特殊 字符 You have to escape it use \\\\. 您必须使用\\\\.对其进行转义\\\\. .

You need to scape . 你需要造景. with \\\\. \\\\. . . means any character. 表示任何字符。

str.replaceAll("\\.","/");   

Read more . 阅读更多

Since dot(.) matches any character 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. 由于dot(.)匹配任何字符,因此在点之前需要两个反斜杠,一个用于使斜杠转义以使其通过,而另一个则用于使点转义以使其变为文字。

String str = "com.sac.src.abc.def";
System.out.println(str.replaceAll("\\.","/"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM