正则表达式划分CSV

来源:互联网 发布:mac 听写 插件 编辑:程序博客网 时间:2024/06/05 04:15
《精通正则表达式》 第401页

    public static ListsplitCSV(String txt) {

       String reg = "\\G(?:^|,)(?:\"([^\"]*+(?:\"\"[^\"]*+)*+)\"|([^\",]*+))";
     // 即 \G(?:^|,)(?:"([^"]*+(?:""[^"]*+)*+)"|([^",]*+))

       Matcher matcherMain =Pattern.compile(reg).matcher("");
       Matcher matcherQuoto =Pattern.compile("\"\"").matcher("");

       matcherMain.reset(txt);
      System.out.println(matcherMain.groupCount());
       List strList = new ArrayList();
       while (matcherMain.find()) {
           Stringfield;
           if(matcherMain.start(2) >= 0) {
              field =matcherMain.group(2);
           } else{
              field =matcherQuoto.reset(matcherMain.group(1)).replaceAll("\"");
           }
          strList.add(field);
       }
       return strList;
    }

  //测试
  public staticvoid main(String[] args) {
       String txt= "The Thousand,10000, 2700,,\"10,000\",\"It's \"\"10 Grand\"\",baby\",10K ";
       //即 The Thousand,10000, 2700,,"10,000","It's ""10 Grand"",baby",10K 
       Listsplits = splitCSV(txt);
       for(String s : splits) {
          System.out.println(s);
       }
   }

打印:
2
The Thousand
10000
 2700 

10,000
It's "10 Grand",baby
10K 

0 0