2013-03-17 65 views
1

我必須編寫一個正則表達式來解析每個CSV行,例如,正則表達式將匹配一個雙引號字符串,其中包含偶數雙引號(「),而不是單引號。Regex表達式匹配偶數的雙引號(「)不匹配單一的CSV

例如,CSV分隔符是選項卡\ t。我有這樣一行:

"first column ""end"\tsecond column\t"third \nNewLine\rcolumn\tend" 

正則表達式表達可以讓我提煉出三列如下圖所示:

first column ""end 
second column 
third \nNewLine\rcolumn\tend 

請注意,在第一列中有兩個雙引號,但它可以讓偶數的雙引號。

請注意,在第三列中有\ t和\ r。

如果易於編寫正則表達式,則可以引用第一列和第三列。

有什麼想法?

+0

我已經嘗試過,但我無法弄清楚如何處理引用字符串中偶數個雙引號的場景。 – Pingpong 2013-03-17 18:34:08

回答

2

如果且僅當偶數個引號出現時,如何在選項卡上進行拆分?

splitArray = Regex.Split(subject, 
    @"\t  # Match a tab 
    (?=   # if the following regex matches after it: 
    (?:  # Match... 
     [^""]*"" # Any number of non-quotes, followed by a quote 
     [^""]*"" # ditto, to ensure an even number of quotes 
    )*   # Repeat as many times as needed 
    [^""]*  # Then match any remaining non-quote characters 
    $   # until the end of the string. 
    )   # End of lookahead assertion", 
    RegexOptions.IgnorePatternWhitespace); 
+0

@Tim Pietzcker你如何實現你的正則表達式級別。你能推薦學習方法和學習材料嗎? – Pingpong 2013-03-17 19:37:46

+0

@Pingpong:我從使用[RegexBuddy](http://www.regexbuddy.com)及其教程,以及閱讀弗裏德爾的「掌握正則表達式」中學到了很多東西。 – 2013-03-17 20:50:18