Regex pattern for split

前端 未结 2 1009
傲寒
傲寒 2020-12-22 15:56

I would like to resolve this problem.

  • , comma : split terms
  • \" double quote : String value (ignore special char)
  • <
2条回答
  •  时光取名叫无心
    2020-12-22 16:17

    This regex does the trick:

    ",(?=(([^\"]*\"){2})*[^\"]*$)(?=([^\\[]*?\\[[^\\]]*\\][^\\[\\]]*?)*$)"
    

    It works by adding a look-ahead for matching pairs of square brackets after the comma - if you're inside a square-bracketed term, of course you won't have balanced brackets following.

    Here's some test code:

    String line = "a=1,b=\"1,2,3\",c=[d=1,e=\"1,11\"]";
    String[] tokens = line.split(",(?=(([^\"]*\"){2})*[^\"]*$)(?=([^\\[]*?\\[[^\\]]*\\][^\\[\\]]*?)*$)");
    for (String t : tokens)
        System.out.println(t);
    

    Output:

    a=1
    b="1,2,3"
    c=[d=1,e="1,11"]
    

提交回复
热议问题