繁体   English   中英

Java:拆分逗号分隔的字符串但忽略引号中的逗号

[英]Java: splitting a comma-separated string but ignoring commas in quotes

我有一个模糊的字符串:

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

我想用逗号分隔 - 但我需要忽略引号中的逗号。 我怎样才能做到这一点? 似乎正则表达式方法失败了; 我想我可以在看到报价时手动扫描并输入不同的模式,但是使用预先存在的库会很好。 编辑:我想我的意思是已经是 JDK 的一部分或者已经是 Apache Commons 等常用库的一部分的库。)

上面的字符串应该分成:

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

注意:这不是 CSV 文件,它是包含在具有更大整体结构的文件中的单个字符串

尝试:

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"

换句话说:仅当逗号前面有零个或偶数个引号时才拆分逗号

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

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

产生与第一个示例相同的结果。

编辑

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

我更喜欢使用Guava 的 Splitter ,因为它具有更合理的默认值(参见上面关于String#split()修剪空匹配的讨论,所以我这样做了:

 Splitter.on(Pattern.compile(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"))

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

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(","));

我不建议 Bart 给出正则表达式的答案,我发现在这种特殊情况下解析解决方案更好(正如 Fabian 建议的那样)。 我已经尝试过正则表达式解决方案和自己的解析实现,我发现:

  1. 解析比使用带有反向引用的正则表达式拆分要快得多 - 短字符串快约 20 倍,长字符串快约 40 倍。
  2. 正则表达式在最后一个逗号后找不到空字符串。 但这不是最初的问题,这是我的要求。

我的解决方案和测试如下。

String tested = "foo,bar,c;qual=\"baz,blurb\",d;junk=\"quux,syzygy\",";
long start = System.nanoTime();
String[] tokens = tested.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
long timeWithSplitting = System.nanoTime() - start;

start = System.nanoTime(); 
List<String> tokensList = new ArrayList<String>();
boolean inQuotes = false;
StringBuilder b = new StringBuilder();
for (char c : tested.toCharArray()) {
    switch (c) {
    case ',':
        if (inQuotes) {
            b.append(c);
        } else {
            tokensList.add(b.toString());
            b = new StringBuilder();
        }
        break;
    case '\"':
        inQuotes = !inQuotes;
    default:
        b.append(c);
    break;
    }
}
tokensList.add(b.toString());
long timeWithParsing = System.nanoTime() - start;

System.out.println(Arrays.toString(tokens));
System.out.println(tokensList.toString());
System.out.printf("Time with splitting:\t%10d\n",timeWithSplitting);
System.out.printf("Time with parsing:\t%10d\n",timeWithParsing);

当然,如果您对它的丑陋感到不舒服,您可以自由地将 switch 更改为此代码段中的 else-ifs。 请注意,使用分隔符切换后缺少中断。 StringBuilder 被设计用来代替 StringBuffer 以提高速度,其中线程安全无关紧要。

您处于正则表达式几乎不会做的那个烦人的边界区域(正如 Bart 指出的那样,转义引号会使生活变得艰难),但是成熟的解析器似乎有点矫枉过正。

如果您可能很快需要更大的复杂性,我会去寻找一个解析器库。 比如 这个

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

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

(读者练习:通过查找反斜杠扩展到处理转义的引号。)

尝试像(?!\"),(?!\")这样的环顾四周 这应该匹配,没有被"包围。

最简单的方法是不使用复杂的附加逻辑来匹配分隔符,即逗号,以匹配实际预期的内容(可能是引用字符串的数据),只是为了排除错误的分隔符,而是首先匹配预期的数据。

该模式由两个替代方案组成,带引号的字符串( "[^"]*"".*?" )或直到下一个逗号的所有内容( [^,]+ )。为了支持空单元格,我们必须允许未加引号的项目为空并使用下一个逗号(如果有),并使用\\G锚:

Pattern p = Pattern.compile("\\G\"(.*?)\",?|([^,]*),?");

该模式还包含两个捕获组以获取引用字符串的内容或纯内容。

然后,使用 Java 9,我们可以得到一个数组

String[] a = p.matcher(input).results()
    .map(m -> m.group(m.start(1)<0? 2: 1))
    .toArray(String[]::new);

而较旧的 Java 版本需要一个循环

for(Matcher m = p.matcher(input); m.find(); ) {
    String token = m.group(m.start(1)<0? 2: 1);
    System.out.println("found: "+token);
}

将项目添加到List或数组中,留给读者作为消费税。

对于 Java 8,您可以使用此答案results()实现,就像 Java 9 解决方案一样。

对于带有嵌入字符串的混合内容,例如问题中,您可以简单地使用

Pattern p = Pattern.compile("\\G((\"(.*?)\"|[^,])*),?");

但是,字符串会保留在引用的形式中。

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

这是我在 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.split() 的单线如何?

String s = "foo,bar,c;qual=\"baz,blurb\",d;junk=\"quux,syzygy\"";
String[] split = s.split( "(?<!\".{0,255}[^\"]),|,(?![^\"].*\")" );

我会做这样的事情:

boolean foundQuote = false;

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

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

else 

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM