2011-12-22 49 views
0

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

} 
+0

如果需要,它更有用的鏈接到另一個答案,比複製整個事情沒有任何參考。 – stema 2011-12-22 15:33:15

回答

1

我儘量給你提示和必要的詞彙來找到regular-expressions.info

"([^\"]*)"|(?<=,|^)([^,])(?:,|$) 

()很好的解釋是一組

*是一個量詞

如果有後?右左括號那麼它是一個特殊的羣體,在這裏(?<=,|^)是向後斷言。

方括號聲明一個字符類,例如[^\"]。這是一個特殊的,因爲^在開始。這是一個否定的角色類。

|表示交替,即OR運算符。

(?:,|$)是非捕獲組

$是在正則表達式一個特殊字符,它是一種錨(其字符串的末尾匹配)

0
"([^\"]*)"|(?<=,|^)([^,]*)(?:,|$) 
() capture group 
(?:) non-capture group 
[] any character within the bracket matches 
\ escape character used to match operators aka " 
(?<=) positive lookbehind (looks to see if the contained matches before the marker) 
| either or operator (matches either side of the pipe) 
^ beginning of line operator 
* zero or more of the preceding character 
$ or \z end of line operator 

對於未來的參考請收藏一個a good regex reference它可以很好地解釋每個部分。