Regex : Split on comma , but exclude commas within parentheses and quotes(Both single & Double)

前端 未结 3 967
甜味超标
甜味超标 2021-01-15 13:55

I have one string

5,(5,5),C\'A,B\',\'A,B\',\',B\',\'A,\',\"A,B\",C\"A,B\" 

I want to split it on comma but need to exclude commas within pa

3条回答
  •  星月不相逢
    2021-01-15 14:25

    Instead of splitting the string, consider matching instead.

    String s  = "5,(5,5),C'A,B','A,B',',B','A,',\"A,B\",C\"A,B\"";
    Pattern p = Pattern.compile("(?:[^,]*(['\"])[^'\"]*\\1|\\([^)]*\\))|[^,]+");
    Matcher m = p.matcher(s);
    while (m.find()) {
      System.out.println(m.group());
    }
    

    Output

    5
    (5,5)
    C'A,B'
    'A,B'
    ',B'
    'A,'
    "A,B" 
    C"A,B"
    

提交回复
热议问题