2011-12-22 52 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它可以很好地解释每个部分。