Java: Replace all ' in a string with \'

前端 未结 6 454
北恋
北恋 2020-12-29 04:30

I need to escape all quotes (\') in a string, so it becomes \\\'

I\'ve tried using replaceAll, but it doesn\'t do anything. For some reason I can\'t get the regex to

6条回答
  •  囚心锁ツ
    2020-12-29 05:34

    This doesn't say how to "fix" the problem - that's already been done in other answers; it exists to draw out the details and applicable documentation references.


    When using String.replaceAll or any of the applicable Matcher replacers, pay attention to the replacement string and how it is handled:

    Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

    As pointed out by isnot2bad in a comment, Matcher.quoteReplacement may be useful here:

    Returns a literal replacement String for the specified String. .. The String produced will match the sequence of characters in s treated as a literal sequence. Slashes (\) and dollar signs ($) will be given no special meaning.

提交回复
热议问题