簡體   English   中英

Java 1.4 String.replaceAll問題帶有單引號

[英]Java 1.4 String.replaceAll issue with single quote

我有一個來自必須放入JSON的數據庫的字符串值,但是該值可以包含單引號和雙引號。 聽起來很容易,對吧? 好吧,顯然不是在Java 1.4.2中。 不要讓我開始介紹為什么它必須是1.4.2,我是從另一個開發人員那里繼承而來的,由於我無法控制的因素,我們還不能更新該項目。 :)

因此,我已經嘗試了所有這些方法(還有很多其他方法只是為了查看結果):

"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"

我想要的只是sample user\\'s string ,我在做什么錯? 太糟糕了1.4.2沒有String.replace(String,String)函數。

編輯 :我們正在使用json-simple JSON庫,我正在結果JSON字符串中查看上述命令的輸出。 我添加了其他調試信息以在JSON輸出之前查看該值,並且看起來上述命令確實有效,但是json-simple庫正在剝離轉義字符。

所以,我看到的是:

"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

因此,圖書館似乎沒有按預期完成其工作。 使用json-simple人是否知道解決方法?

我懷疑您是在自動為您轉義反斜杠的上下文中查看字符串。 您倒數第二個樣品應該沒問題。 例如:

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

印刷品:

sample user\'s string

您沒有說要在哪里查看該值,但是如果它在調試器中,則很可能會使您的反斜杠加倍,以便像使用Java文字一樣顯示該值。

不過,理想情況下,您不應該手動執行此類操作-太容易出錯了。 您應該使用一個為您處理所有這些的JSON庫,因此您需要指定值即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM