简体   繁体   中英

String functions - replaceAll not working for “.”

I was going through replaceAll function. 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:

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

"." is a special character in REGEX world and replaceAll takes regex as first input parameter in the method. Since you are not using regex already, use replace method.

. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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