發現這段代碼中爆發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