Java replace issues with ' (apostrophe/single quote) and \ (backslash) together

前端 未结 7 1597
梦毁少年i
梦毁少年i 2021-01-30 18:03

I seem to be having issues. I have a query string that has values that can contain single quotes. This will break the query string. So I was trying to do a replace to change

相关标签:
7条回答
  • 2021-01-30 18:12

    If you want to use it in JavaScript then you can use

    str.replace("SP","\\SP");
    

    But in Java

    str.replaceAll("SP","\\SP");
    

    will work perfectly.

    SP: special character

    Otherwise you can use Apache's EscapeUtil. It will solve your problem.

    0 讨论(0)
  • 2021-01-30 18:22

    I have used a trick to handle the apostrophe special character. When replacing ' for \' you need to place four backslashes before the apostrophe.

    str.replaceAll("'","\\\\'");
    
    0 讨论(0)
  • 2021-01-30 18:24

    Use "This is' it".replace("'", "\\'")

    0 讨论(0)
  • 2021-01-30 18:24

    I have used

    str.replace("'", "");
    

    to replace the single quote in my string. Its working fine for me.

    0 讨论(0)
  • 2021-01-30 18:32

    First of all, if you are trying to encode apostophes for querystrings, they need to be URLEncoded, not escaped with a leading backslash. For that use URLEncoder.encode(String, String) (BTW: the second argument should always be "UTF-8"). Secondly, if you want to replace all instances of apostophe with backslash apostrophe, you must escape the backslash in your string expression with a leading backslash. Like this:

    "This is' it".replace("'", "\\'");
    

    Edit:

    I see now that you are probably trying to dynamically build a SQL statement. Do not do it this way. Your code will be susceptible to SQL injection attacks. Instead use a PreparedStatement.

    0 讨论(0)
  • 2021-01-30 18:32

    Remember that stringToEdit.replaceAll(String, String) returns the result string. It doesn't modify stringToEdit because Strings are immutable in Java. To get any change to stick, you should use

    stringToEdit = stringToEdit.replaceAll("'", "\\'");
    
    0 讨论(0)
提交回复
热议问题