如何在Java中按空格拆分字符串但忽略引号内的空格?

6

我有一个字符串:

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

我希望按空格分割它,但是引号内的空格应该被忽略。 因此,分割后的字符串应该是:

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

这个技术涉及的编程语言是Java。


1
在您的情况下,如何转义 "?例如 "he said \"hi\"." - Daniel Moses
5个回答

6
这应该能为您完成工作:
   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"

4

您可以使用:

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

2

1

不要使用分割,只匹配非空格的内容。

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

0

改用"[ ]+"进行分割?(包括引号)

如果字符串的开头或结尾没有引号,你可能需要添加缺失的引号。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接