繁体   English   中英

我如何正则表达式从文本中删除空格和换行符,除非它们在json的字符串中?

[英]How do I regex remove whitespace and newlines from a text, except for when they are in a json's string?

我有一条指令,如:

db.insert( {
    _id:3,
    cost:{_0:11},
    description:"This is a description.\nCool, isn\'t it?"
});

我正在使用的名为MonjaDB的Eclipse插件按换行符拆分指令,我将每一行作为单独的指令获取,这很糟糕。 我使用;(\\ r | \\ n)+修复了该问题,现在它包含了整个指令,但是,当清理JSON部分之间的换行符时,它还清理了json本身的字符串中的\\ n和\\ r。

如何避免从JSON字符串中删除\\ t,\\ r,\\ n? 当然用“”或“”分隔。

当空格出现在引号中时,您需要安排忽略空格。 因此,正如其中一位评论者所建议的那样:

\s+ | ( "  (?: [^"\\]  |  \\ . ) * " )              // White-space inserted for readability

匹配java空格或双引号字符串,其中字符串包含"后跟任何非转义,非引号或转义+加上任何字符,然后是最后一个" 这样,字符串内的空格将不匹配。

如果$ 1不为空,则替换为$ 1。

    Pattern clean = Pattern.compile(" \\s+ | ( \" (?: [^\"\\\\] | \\\\ . ) * \" ) ", Pattern.COMMENTS | Pattern.DOTALL);

StringBuffer sb = new StringBuffer();
Matcher m = clean.matcher( json );
while (m.find()) {
    m.appendReplacement(sb, "" );
    // Don't put m.group(1) in the appendReplacement because if it happens to contain $1 or $2 you'll get an error.
    if ( m.group(1) != null )
        sb.append( m.group(1) );
}
m.appendTail(sb);

String cleanJson = sb.toString();

这完全不在我的脑海中,但是我很确定它已经接近您想要的。

编辑:我刚刚可以访问Java IDE,并尝试了我的解决方案。 我在代码中犯了一些错误,包括使用\\. 代替. 在模式中。 因此,我已对其进行修复,并在您的样本变体中运行它:

db.insert( {
    _id:3,
    cost:{_0:11},
    description:"This is a \"description\" with an embedded newline: \"\n\".\nCool, isn\'t it?"
});

编码:

    String json = "db.insert( {\n" +
            "    _id:3,\n" +
            "    cost:{_0:11},\n" +
            "    description:\"This is a \\\"description\\\" with an embedded newline: \\\"\\n\\\".\\nCool, isn\\'t it?\"\n" +
            "});";

        // insert above code

        System.out.println(cleanJson);

这将产生:

db.insert({_id:3,cost:{_0:11},description:"This is a \"description\" with an embedded newline: \"\n\".\nCool, isn\'t it?"});

这是相同的json表达式,其中所有带引号的字符串都删除了空白,而带引号的字符串内保留了换行符和换行符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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