【问题标题】:Escape rogue backslashes in a string转义字符串中的流氓反斜杠
【发布时间】:2019-07-31 10:07:40
【问题描述】:

我在数据库中有一个这样的 JSON 字符串:

{"name" : "DROCK", "details" : [{"age" : "23", "degree" : "BE", "Experience" : "worked in a company\6as an intern"}]}

我想删除 \ 字符,但它不是有效的转义字符串。我尝试使用 StringEscapeUtil,但它在这里没有帮助我。

我在这里使用的代码:

import org.apache.commons.lang.xwork.StringEscapeUtils;

public class JSONEscape {
    public static void main(String args[]) {
        String testString = "{\"name\" : \"DROCK\", \"details\" : [{\"age\" : \"23\", \"degree\" : \"BE\", \"Experience\" : \"worked in a company\6as an intern\"}]}";
        System.out.println(StringEscapeUtils.escapeJava(testString));
    }
}

我应该如何转义有效的 \ 字符并删除这样的流氓字符。但我想保留有效的转义字符,如 \n、\t 等。

最后我想要这样的结果:

{"name" : "DROCK", "details" : [{"age" : "23", "degree" : "BE", "Experience" : "worked in a company6as an intern"}]}

【问题讨论】:

    标签: java json regex


    【解决方案1】:

    如果您想删除 JSON 字符串中的错误转义序列,那么这很容易。

    String testString = "{\"name\" : \"DROCK\", \"details\" : [\"age\" : \"23\", \"degree\" : \"BE\", \"Experience\" : \"worked in a company\\6as an intern\"]}";
    System.out.println(testString.replaceAll("\\([^bfnrt\"\\])", "$1"));
    

    RegEx 的字面意思只是“反斜杠后面跟着一个无效的转义字符,去掉反斜杠”。

    【讨论】:

    • 感谢@Leo Aso 的回复,我修改了替换字符串如下: System.out.println(testString.replaceAll("\\[^bfnrt\"\'\\]", " $1")); 现在我可以看到 ? 代替 SOP 中的 6 :(
    • 确保在您的测试字符串中输入\\6 而不是\6。如果直接在字符串中键入 JSON,则需要写两次反斜杠,因为 Java 将 \6 识别为等于 \u0006 的转义序列,但如果键入 \\6,它只会将其保留为 @987654327 @.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-08
    • 1970-01-01
    相关资源
    最近更新 更多