我有一个这样的字符串:
foo,bar,c;qual="baz,blurb",d;junk="quux,syzygy"
我想用逗号分隔,但我需要忽略引号中的逗号。我该怎么做呢?regexp方法似乎失败了;我想我可以手动扫描,并在看到报价时进入不同的模式,但如果使用已有的库就更好了。(编辑:我想我指的是已经是JDK的一部分或者已经是Apache Commons等常用库的一部分的库。)
上面的字符串应该分成:
foo
bar
c;qual="baz,blurb"
d;junk="quux,syzygy"
注意:这不是一个CSV文件,它是一个包含在一个更大的整体结构文件中的单个字符串
使用String.split()的一行程序怎么样?
String s = "foo,bar,c;qual=\"baz,blurb\",d;junk=\"quux,syzygy\"";
String[] split = s.split( "(?<!\".{0,255}[^\"]),|,(?![^\"].*\")" );
我没有耐心,没有选择等待答案。作为参考,它看起来并不难做这样的事情(这适用于我的应用程序,我不需要担心转义引号,因为引号中的东西仅限于几个约束形式):
final static private Pattern splitSearchPattern = Pattern.compile("[\",]");
private List<String> splitByCommasNotInQuotes(String s) {
if (s == null)
return Collections.emptyList();
List<String> list = new ArrayList<String>();
Matcher m = splitSearchPattern.matcher(s);
int pos = 0;
boolean quoteMode = false;
while (m.find())
{
String sep = m.group();
if ("\"".equals(sep))
{
quoteMode = !quoteMode;
}
else if (!quoteMode && ",".equals(sep))
{
int toPos = m.start();
list.add(s.substring(pos, toPos));
pos = m.end();
}
}
if (pos < s.length())
list.add(s.substring(pos));
return list;
}
(读者练习:也可以通过寻找反斜杠来处理转义引号。)
正则表达式不能处理转义字符。对于我的应用程序,我需要能够转义引号和空格(分隔符是空格,但代码是相同的)。
以下是我在Kotlin(来自这个特定应用程序的语言)中的解决方案,基于Fabian Steeg的解决方案:
fun parseString(input: String): List<String> {
val result = mutableListOf<String>()
var inQuotes = false
var inEscape = false
val current = StringBuilder()
for (i in input.indices) {
// If this character is escaped, add it without looking
if (inEscape) {
inEscape = false
current.append(input[i])
continue
}
when (val c = input[i]) {
'\\' -> inEscape = true // escape the next character, \ isn't added to result
',' -> if (inQuotes) {
current.append(c)
} else {
result += current.toString()
current.clear()
}
'"' -> inQuotes = !inQuotes
else -> current.append(c)
}
}
if (current.isNotEmpty()) {
result += current.toString()
}
return result
}
我认为这不是一个使用正则表达式的地方。与其他观点相反,我不认为解析器是多余的。它大约有20行,并且相当容易测试。