Kruti Patel Kruti Patel - 1 year ago 137
Java Question

Difference in behaviour between String.replaceAll() and StringUtils.replace()

I want to replace all single quotes with escaped single quotes. First I have tried with

String.replaceAll("\'", "\\'")
but it didn't worked. So, I have tried with
StringUtils.replace(String, "\'", "\\'")
which worked.

Here is the code:

String innerValue = "abc'def'xyz";
System.out.println("stringutils output:"+StringUtils.replace(innerValue, "\'", "\\'"));
System.out.println("replaceAll output:"+innerValue.replaceAll("\'", "\\'"));

Expected Output:

stringutils output:abc\'def\'xyz
replaceAll output:abc\'def\'xyz

Actual Output:

stringutils output:abc\'def\'xyz
replaceAll output:abc'def'xyz

I am just curious Why
is not replacing

Answer Source

You don't need to escape the single quote in Strings (only in char values), and you need a double-double escape with the replacement value:

innerValue.replaceAll("'", "\\\\'")

This is due to replaceAll taking regular expressions as arguments (the second parameter must support regular expressions for back references).

You can also use the replace idiom, since you're not using regular expressions:

innerValue.replace("'", "\\'")


The replace method actually uses replaceAll behind the scenes, but transforms values into literals by invoking Pattern.compile with the Pattern.LITERAL flag, and Matcher.quoteReplacement on the replacement.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download