split string on comma, but not commas inside parenthesis

后端 未结 3 2038
没有蜡笔的小新
没有蜡笔的小新 2021-01-23 23:09

Now I have a task about Java IO , I need to read file line by line and save this data into database, But Now I got a problem.

\"desk\",\"12\",\"15\",\"(small         


        
相关标签:
3条回答
  • 2021-01-23 23:37
    (\(.+?\)|\w+)
    

    the code above matches the result below this will allow for a more flexible solution that some of the other posted ones. The syntax for the regular expression is in another answer on this page just use this regular expression instead

    desk
    12
    15
    (small,median,large)
    0 讨论(0)
  • 2021-01-23 23:43

    You could solve this by using Pattern and Matcher. Any solution using split would just seem like a nasty workaround. Here's an example:

    public static void main(String[] args){
        String s = "\"desk\",\"12\",\"15\",\"(small,median,large)\"";
        Pattern p = Pattern.compile("\".+?\"");
        Matcher m = p.matcher(s);
        List<String> matches = new ArrayList<String>();
    
        while (m.find()){
            matches.add(m.group());
        }
    
        System.out.println(matches);
    }
    
    0 讨论(0)
  • 2021-01-24 00:02

    or, if Java must be:), you can split by "\\s*\"\\s*,\\s*\"" and add afterwards the " if necessary to the beginning of the first field and to the end of the second. I put \s because I see that you also have blanks separators - 15",blank"(small

    0 讨论(0)
提交回复
热议问题