我有一个字符串:
"Video or movie" "parent" "Media or entertainment" "1" "1" "1" "0" "0"
我希望按空格分割它,但是引号内的空格应该被忽略。 因此,分割后的字符串应该是:
"Video or movie"
"parent"
"Media or entertainment"
"1"
...
这个技术涉及的编程语言是Java。
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"
您可以使用:
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"]
不要使用分割,只匹配非空格的内容。
Pattern p = Pattern.compile("\"(?:[^\"\\\\]|\\\\.)*\"|\\S+");
Matcher m = p.matcher(inputString);
while (m.find()) {
System.out.println(m.group(0));
}
改用"[ ]+"进行分割?(包括引号)
如果字符串的开头或结尾没有引号,你可能需要添加缺失的引号。
"
?例如"he said \"hi\"."
? - Daniel Moses