简体   繁体   English

从行中删除双引号

[英]Remove double quotes from line

I have a string that looks like this 我有一个看起来像这样的字符串

"He said, ""What?""" “他说,”“什么?”“”

In the entire file, there's actually more lines like that, separated by commas. 在整个文件中,实际上有更多这样的行,用逗号分隔。 The output of that line should look something like this: 该行的输出应如下所示:

He said, "What?!!" 他说,“什么?!!”

I'm trying to do that by using this method: 我试图通过使用此方法来做到这一点:

Pattern pattern = Pattern.compile("\\s*(\"[^\"]*\"|[^,]*)\\s*");
            Matcher matcher = pattern.matcher(line);
            while (matcher.find()) 
            {
                System.out.println(matcher.group(1));
                lines.add(matcher.group(1)); //adds each line to an arraylist
            }

However, the output I'm getting is this: 但是,我得到的输出是这样的:

He said,
What?

I'm pretty sure the cause is with my regular expressions since all this does is remove all the double quotes. 我很确定原因是我的正则表达式,因为这一切都是删除所有的双引号。

为什么不使用String#replaceAll

line.replaceAll("\"", "");

It's because your regular expression matches 这是因为你的正则表达式匹配

"He said, "

then 然后

"What?"

then 然后

""

It seems like what you actually want is to remove one level of double-quotes. 看起来你真正想要的是删除一级双引号。 To do that, you need to use lookaround assertions: 为此,您需要使用环绕声断言:

Pattern pattern = Pattern.compile("\\s*\"(?!\")[^\"]*(?<!\")\"\\s*");

The process of forming quoted string is: 形成引用字符串的过程是:

  1. Escape (double) the double quotes in the string 转义(双)字符串中的双引号
  2. Surround the resulting string with double quotes 用双引号括起结果字符串

The code below just reverses this process: 下面的代码只是颠倒了这个过程:

It first removes the outer double quotes, then un-escapes the inner double quotes, and then splits: 它首先删除外部双引号,然后取消内部双引号,然后拆分:

public static void main(String[] args) {
    String input = "\"He said, \"\"What?\"\"\"";
    String[] out = input.replaceAll("^(\")|(\")$", "").replace("\"\"", "\"").split(", ");
    for (String o : out) {
        System.out.println(o);
    }
}

Output: 输出:

He said
"What?"

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

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