CSV 文件的格式:
1,每个字段采用逗号分隔;
2,字段中若有逗号的话,则字段两边放上引号(");
3,字段中若出现引号(")则采用两个引号("")表示,并在字段的两边放上引号(")。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
String str = "dw,\"kk,ll\",\",yioi\",iu,\",\",r3,\"\"\"fte\",l,\"kk\"\"ll\",mm'oo,\"n\"\"dw,erw\"\",e\",, ";
String regex = "\\G(?:^|,)(?:\"([^\"]*+(?:\"\"[^\"]*+)*+)\"|([^\",]*+))";
Matcher main = Pattern.compile(regex).matcher(str);
Matcher mquote = Pattern.compile("\"\"").matcher("");
while (main.find()) {
String field;
if (main.start(2) >= 0) {
field = main.group(2);
} else {
field = mquote.reset(main.group(1)).replaceAll("\"");
}
System.out.println("Field [" + field + "]");
}
System.out.println("解析后应产生的字符串:\n" +
"dw\n" + "kk,ll\n" + ",yioi\n" + "iu\n" +
",\n" + "r3\n" + "\"fte\n" + "l\n" +
"kk\"ll\n" + "mm'oo\n" + "n\"dw,erw\",e");
}
}
专家写的表达式,已经高度优化过了,建议收藏一下,没必要去深究。
转自:Jeffrey E.F.Friedl, Mastering Regular Expressions, 3rd ed., 8.9.1. Parsing Comma-Separated Values (CSV) Text. 原文的表达式是采用行内嵌注释模式书写的,这里将其合并了。