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");
System.out.println(s);


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.

Solution:

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

No comments:

Post a Comment