我有一个这样的字符串:

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文件,它是一个包含在一个更大的整体结构文件中的单个字符串


当前回答

Try:

public class Main { 
    public static void main(String[] args) {
        String line = "foo,bar,c;qual=\"baz,blurb\",d;junk=\"quux,syzygy\"";
        String[] tokens = line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);
        for(String t : tokens) {
            System.out.println("> "+t);
        }
    }
}

输出:

> foo
> bar
> c;qual="baz,blurb"
> d;junk="quux,syzygy"

换句话说:仅当逗号前面有0个引号或偶数个引号时,才在逗号上进行分隔。

或者,对眼睛更友好一点:

public class Main { 
    public static void main(String[] args) {
        String line = "foo,bar,c;qual=\"baz,blurb\",d;junk=\"quux,syzygy\"";
        
        String otherThanQuote = " [^\"] ";
        String quotedString = String.format(" \" %s* \" ", otherThanQuote);
        String regex = String.format("(?x) "+ // enable comments, ignore white spaces
                ",                         "+ // match a comma
                "(?=                       "+ // start positive look ahead
                "  (?:                     "+ //   start non-capturing group 1
                "    %s*                   "+ //     match 'otherThanQuote' zero or more times
                "    %s                    "+ //     match 'quotedString'
                "  )*                      "+ //   end group 1 and repeat it zero or more times
                "  %s*                     "+ //   match 'otherThanQuote'
                "  $                       "+ // match the end of the string
                ")                         ", // stop positive look ahead
                otherThanQuote, quotedString, otherThanQuote);

        String[] tokens = line.split(regex, -1);
        for(String t : tokens) {
            System.out.println("> "+t);
        }
    }
}

结果和第一个例子一样。

EDIT

正如@MikeFHay在评论中提到的:

我更喜欢使用Guava的Splitter,因为它有更理智的默认值(见上面关于空匹配被String#split()修剪的讨论,所以我这样做了: Splitter.on (Pattern.compile (",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"))

其他回答

正则表达式不能处理转义字符。对于我的应用程序,我需要能够转义引号和空格(分隔符是空格,但代码是相同的)。

以下是我在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行,并且相当容易测试。

与其使用超前和其他疯狂的正则表达式,不如先取出引号。也就是说,对于每个引号分组,将该分组替换为__IDENTIFIER_1或其他指示符,并将该分组映射为string,string的映射。

在使用逗号分隔之后,将所有映射的标识符替换为原始字符串值。

虽然我一般喜欢正则表达式,但对于这种依赖于状态的标记化,我相信一个简单的解析器(在这种情况下,它比这个词听起来要简单得多)可能是一个更干净的解决方案,特别是在可维护性方面,例如:

String input = "foo,bar,c;qual=\"baz,blurb\",d;junk=\"quux,syzygy\"";
List<String> result = new ArrayList<String>();
int start = 0;
boolean inQuotes = false;
for (int current = 0; current < input.length(); current++) {
    if (input.charAt(current) == '\"') inQuotes = !inQuotes; // toggle state
    else if (input.charAt(current) == ',' && !inQuotes) {
        result.add(input.substring(start, current));
        start = current + 1;
    }
}
result.add(input.substring(start));

如果你不关心保留引号内的逗号,你可以简化这种方法(不处理开始索引,没有最后一个字符的特殊情况),用其他东西替换引号中的逗号,然后以逗号分隔:

String input = "foo,bar,c;qual=\"baz,blurb\",d;junk=\"quux,syzygy\"";
StringBuilder builder = new StringBuilder(input);
boolean inQuotes = false;
for (int currentIndex = 0; currentIndex < builder.length(); currentIndex++) {
    char currentChar = builder.charAt(currentIndex);
    if (currentChar == '\"') inQuotes = !inQuotes; // toggle state
    if (currentChar == ',' && inQuotes) {
        builder.setCharAt(currentIndex, ';'); // or '♡', and replace later
    }
}
List<String> result = Arrays.asList(builder.toString().split(","));

我会这样做:

boolean foundQuote = false;

if(charAtIndex(currentStringIndex) == '"')
{
   foundQuote = true;
}

if(foundQuote == true)
{
   //do nothing
}

else 

{
  string[] split = currentString.split(',');  
}

我没有耐心,没有选择等待答案。作为参考,它看起来并不难做这样的事情(这适用于我的应用程序,我不需要担心转义引号,因为引号中的东西仅限于几个约束形式):

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;
}

(读者练习:也可以通过寻找反斜杠来处理转义引号。)