发现这段代码中爆发CSV字段是否包含双引号 但我真的不明白,从正则表达式解释工作正则表达式表达
匹配模式。如果有人可以给我用的怎么样这一步解释的一步表达式的计算结果,将可以理解
"([^\"]*)"|(?<=,|^)([^,]*)(?:,|$)
由于
==== 旧张贴
图案这对我来说很好 - 或者匹配“两个引号和它们之间的任何内容”,或者“在行首或逗号与行末或逗号之间的内容”。迭代通过比赛可以让我看到所有的场地,即使它们是空的。例如,
的快,“棕色,狐狸跳”过“的” ,,“懒狗”分解成
快“的棕色狐狸跳”过“了”“懒狗“
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CSVParser {
/*
* This Pattern will match on either quoted text or text between commas, including
* whitespace, and accounting for beginning and end of line.
*/
private final Pattern csvPattern = Pattern.compile("\"([^\"]*)\"|(?<=,|^)([^,]*)(?:,|$)");
private ArrayList<String> allMatches = null;
private Matcher matcher = null;
private String match = null;
private int size;
public CSVParser() {
allMatches = new ArrayList<String>();
matcher = null;
match = null;
}
public String[] parse(String csvLine) {
matcher = csvPattern.matcher(csvLine);
allMatches.clear();
String match;
while (matcher.find()) {
match = matcher.group(1);
if (match!=null) {
allMatches.add(match);
}
else {
allMatches.add(matcher.group(2));
}
}
size = allMatches.size();
if (size > 0) {
return allMatches.toArray(new String[size]);
}
else {
return new String[0];
}
}
public static void main(String[] args) {
String lineinput = "the quick,\"brown, fox jumps\",over,\"the\",,\"lazy dog\"";
CSVParser myCSV = new CSVParser();
System.out.println("Testing CSVParser with: \n " + lineinput);
for (String s : myCSV.parse(lineinput)) {
System.out.println(s);
}
}
}
如果需要,它更有用的链接到另一个答案,比复制整个事情没有任何参考。 – stema 2011-12-22 15:33:15