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

前端 未结 11 1556
广开言路
广开言路 2020-11-21 05:16

I have a string vaguely like this:

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

that I want to split by commas -- but I need to igno

11条回答
  •  太阳男子
    2020-11-21 06:08

    I was impatient and chose not to wait for answers... for reference it doesn't look that hard to do something like this (which works for my application, I don't need to worry about escaped quotes, as the stuff in quotes is limited to a few constrained forms):

    final static private Pattern splitSearchPattern = Pattern.compile("[\",]"); 
    private List splitByCommasNotInQuotes(String s) {
        if (s == null)
            return Collections.emptyList();
    
        List list = new ArrayList();
        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;
    }
    

    (exercise for the reader: extend to handling escaped quotes by looking for backslashes also.)

提交回复
热议问题