Splitting a csv file with quotes as text-delimiter using String.split()

前端 未结 3 609
离开以前
离开以前 2020-11-27 11:07

I have a comma separated file with many lines similar to one below.

Sachin,,M,\"Maths,Science,English\",Need to improve in these subjects.

3条回答
  •  有刺的猬
    2020-11-27 11:42

    If your strings are all well-formed it is possible with the following regular expression:

    String[] res = str.split(",(?=([^\"]|\"[^\"]*\")*$)");
    

    The expression ensures that a split occurs only at commas which are followed by an even (or zero) number of quotes (and thus not inside such quotes).

    Nevertheless, it may be easier to use a simple non-regex parser.

提交回复
热议问题