我在stackoverflow上搜索了几篇关于如何在逗号分隔符上拆分字符串的帖子,但忽略了引号中的逗号拆分(请参阅:如何通过逗号将字符串拆分为数组但忽略双引号内的逗号?)我正在尝试以达到类似的结果,但还需要允许包含一个双引号的字符串。
IE。需要"test05, \"test, 05\", test\", test 05"
拆分成
test05
"test, 05"
test"
test 05
我尝试了与此处提到的方法类似的方法:
正则表达式用于在没有被单引号或双引号包围时使用空格分割字符串
使用 Matcher,而不是split()
. 但是,它以空格而不是逗号分隔特定示例。相反,我尝试调整模式以考虑逗号,但没有任何运气。
String str = "test05, \"test, 05\", test\", test 05";
str = str + " "; // add trailing space
int len = str.length();
Matcher m = Pattern.compile("((\"[^\"]+?\")|([^,]+?)),++").matcher(str);
for (int i = 0; i < len; i++)
{
m.region(i, len);
if (m.lookingAt())
{
String s = m.group(1);
if ((s.startsWith("\"") && s.endsWith("\"")))
{
s = s.substring(1, s.length() - 1);
}
System.out.println(i + ": \"" + s + "\"");
i += (m.group(0).length() - 1);
}
}