【问题标题】:how to split string by space but escape spaces inside quotes (in java)? [duplicate]如何按空格分割字符串但在引号内转义空格(在java中)? [复制]
【发布时间】:2012-01-20 17:04:42
【问题描述】:

我有一个这样的字符串:

"Video or movie"    "parent"    "Media or entertainment"    "1" "1" "1" "0" "0"

我想用空格分割它,但引号内的空格应该被忽略。 所以拆分后的字符串应该是:

"Video or movie"
"parent"
"Media or entertainment"
"1"
...

语言是java。

【问题讨论】:

  • " 如何在您的场景中逃脱? "he said \"hi\"."?

标签: java regex string split


【解决方案1】:

这应该为您完成工作:

   final String s = "\"Video or movie\"    \"parent\"    \"Media or entertainment\"    \"1\" \"1\" \"1\" \"0\" \"0\"";
        final String[] t = s.split("(?<=\") *(?=\")");
        for (final String x : t) {
            System.out.println(x);
        }

输出:

"Video or movie"
"parent"
"Media or entertainment"
"1"
"1"
"1"
"0"
"0"

【讨论】:

    【解决方案2】:

    你可以使用:

    Patter pt = Pattern.compile("(\"[^\"]*\")");
    

    请记住,这也会捕获""(空字符串)。

    测试:

    String text="\"Video or movie\"    \"parent\"    \"Media or entertainment\"    \"1\" \"1\" \"1\" \"0\" \"0\"";
    Matcher m = Pattern.compile("(\"[^\"]*\")").matcher(text);
    while(m.find())
        System.out.printf("Macthed: [%s]%n", m.group(1));
    

    输出:

    Macthed: ["Video or movie"]
    Macthed: ["parent"]
    Macthed: ["Media or entertainment"]
    Macthed: ["1"]
    Macthed: ["1"]
    Macthed: ["1"]
    Macthed: ["0"]
    Macthed: ["0"]
    

    【讨论】:

      【解决方案3】:

      看看这个问题。您也许可以调整其解决方案以忽略引号中的空格而不是逗号。

      Java: splitting a comma-separated string but ignoring commas in quotes

      【讨论】:

        【解决方案4】:

        不拆分,只匹配非空格的东西。

        Pattern p = Pattern.compile("\"(?:[^\"\\\\]|\\\\.)*\"|\\S+");
        Matcher m = p.matcher(inputString);
        while (m.find()) {
          System.out.println(m.group(0));
        }
        

        【讨论】:

          【解决方案5】:

          改为由 "[ ]+" 分割? (包括引号)

          如果它们不在字符串的开头或结尾,您可能需要添加缺失的 "。

          【讨论】:

            猜你喜欢
            • 2012-08-03
            • 2013-03-03
            • 1970-01-01
            • 2016-01-07
            • 1970-01-01
            • 2011-01-28
            • 2013-04-22
            • 1970-01-01
            • 2011-12-15
            相关资源
            最近更新 更多