-4

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 String.replaceAll is not replacing ' with \'?

Kruti Patel
  • 1,422
  • 2
  • 23
  • 36
  • 6
    `String.replaceAll` uses regular expressions, where backslashes have special meaning. Use `replace` instead of `reaplceAll`. – Jon Skeet Jul 05 '16 at 12:15
  • 1
    Hint: when standard java library calls do not match up **your** expectations; then your expectations are **wrong**. The easy and simply way to fix that: RTFM. Seriously, don't assume that a method does this or that; just read its javadoc. Or: do some prior research, like **searching** this site before writing up a new question. – GhostCat Jul 05 '16 at 12:22
  • Possible duplicate of [Difference between String replace() and replaceAll()](http://stackoverflow.com/questions/10827872/difference-between-string-replace-and-replaceall) – GhostCat Jul 05 '16 at 12:25

2 Answers2

1

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("'", "\\'")

Note

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.

Mena
  • 47,782
  • 11
  • 87
  • 106
0

Java String Package replaceAll method expects RegularExpression as String parameter. Whereas Commons Lang StringUtils.replace expects String value.

We have to do double escape when it comes to native Java implementation. System.out.println("replaceAll output:"+innerValue.replaceAll("'", "\\'"));

kadalamittai
  • 2,076
  • 1
  • 16
  • 19