【发布时间】:2011-12-22 15:14:48
【问题描述】:
如果包含双引号,则发现此代码会拆分 CSV 字段 但我不太了解正则表达式的模式匹配
如果有人可以逐步解释此表达式如何评估模式,将不胜感激
"([^\"]*)"|(?<=,|^)([^,]*)(?:,|$)
谢谢
==== 旧帖
这对我来说效果很好 - 它可以匹配“两个引号以及它们之间的任何内容”,或者“行首或逗号与行尾或逗号之间的某个内容”。遍历匹配项可以获得所有字段,即使它们是空的。例如,
快速,“棕色,狐狸跳”,over,“the”,“lazy dog”分解成
快速的“棕色,狐狸跳”过“那只”“懒狗”
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);
}
}
}
【问题讨论】:
-
如果需要,链接到另一个答案比在没有任何参考的情况下复制整个内容更有用。