简体   繁体   中英

Java 1.4 String.replaceAll issue with single quote

I've got a string value coming from a database that has to be put into JSON, but the value can contain single and double quotes. Sounds easy enough, right? Well, apparently not in Java 1.4.2. Don't get me started on why it has to be 1.4.2, I inherited this from another developer and we can't update this project yet due to factors beyond my control. :)

So, I have tried all of these (and lots of others just to see the result):

"sample user's string".replaceAll("'", "\'")      // returns "sample user's string"
"sample user's string".replaceAll("'", "\\'")     // returns "sample user's string"
"sample user's string".replaceAll("'", "\\\'")    // returns "sample user's string"
"sample user's string".replaceAll("'", "\\\\'")   // returns "sample user\\'s string"
"sample user's string".replaceAll("'", "%%")      // returns "sample user%%s string"

All I want is sample user\\'s string , what am I doing wrong? Too bad 1.4.2 doesn't have the String.replace(String,String) function.

Edit : We are using the json-simple JSON library and I was looking at the output of the above commands in the resultant JSON string. I added additional debug info to see the value before the JSON gets output and it looks like the above commands really are working, but the json-simple library is stripping the escape chars out.

So, what I'm seeing is:

"sample user's string".replaceAll("'", "\\\\'")    // sample user\'s string
myJSONObject.put("value", "sample user's string".replaceAll("'", "\\\\'")) // sample user\\'s string"
myJSONObject.put("value", "sample user's string") // sample user's string

So it looks like the library is not doing its job quite as expected. Does anyone that has used json-simple know of a workaround for this?

I suspect you're looking at the string in a context which is automatically escaping backslashes for you. Your penultimate sample should be fine. For example:

public class Test {
    public static void main(String[] args) {
        System.out.println("sample user's string".replaceAll("'", "\\\\'"));
    }
}

Prints:

sample user\'s string

You didn't say where you were looking at the value, but if it's in the debugger, that may well be doubling the backslash for you, to present the value as if it were in a Java literal.

Ideally though, you shouldn't be doing this sort of thing manually - it's far too error-prone. You should use a JSON library which handles all of this for you, so you just need to specify the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM