Thursday, September 30, 2010

Pitfalls in replaceAll function of String class

Lets have a look at the replaceAll function.

String s = "Yogesh C:\\test3.xml vaibhav";
s = s.replaceAll("C:\\test3.xml", "test");

You might be expecting that it would replace the string c:\\test3.xml, but it doesn't happens.
Reason :
The regex parser has backslash (\) and dollar ($) as keywords, so it treats it differently.
If your string contains these characters, you can use Matcher.quoteReplacement to skip these characters.


String s = "Yogesh C:\\test3.xml vaibhav";
s = s.replaceAll(Matcher.quoteReplacement("C:\\test3.xml"), "test");

No comments:

Post a Comment