2012-05-09 142 views
2

所以這裏有大量的帖子說明,而不是滾動我自己的csv解析器我應該使用Vb.Net TextFiledParser。正則表達式 - 解析Csv文本

我試過了,但請告訴我,如果我錯了,它會根據單個分隔符進行解析。

因此,如果我有一個地址字段「Flat 1,StackOverflow House,London」,我會得到三個字段。不幸的是,這不是我想要的。我需要給定單元格中的所有內容保持爲數組中的單個項目。

於是我開始寫我自己的正則表達式如下:

var testString = @"""Test 1st string""" + "," + @"""Flat 1, StackOverflow House, London, England, The Earth""" + "," + "123456"; 

var matches = Regex.Matches(chars, @"""([^""\\])*?(?:\\.[^""\\]*)*?"""); 
var numbers = Regex.Matches(chars, @"\d+$");//only numbers 
Assert.That(results.Count(), Is.EqualTo(3)); 
Assert.That(secondMatch.Count, Is.EqualTo(1)); 

第一個斷言失敗爲字符串「123456」,則返回。表達式只返回「Test 1st string」和「Flat 1,StackOverflow House,倫敦,英國,地球」

我想要的是正則表達式返回引用\ escaped和數字的所有內容。

我不控制數據,但數字字符串將被引用\轉義和數字不會。

我非常感謝一些幫助,因爲我正在嘗試使用第三方庫,但沒有取得太大的成功。

不用說string.split在地址的情況下不起作用,並且http://www.filehelpers.com/似乎沒有解釋這樣的例子。

+1

使用正則表達式解析CSV的確是很混亂的,特別是如果你不控制你的輸入。所以除非你可以保證在字符串中不會有任何逃脫的引號,否則你將很難得到一個正則表達式來可靠地完成這項工作。 –

回答

2

只給你一個想法,你在做什麼反對:這裏是一個要工作得非常好正則表達式。但你肯定需要測試一下它,因爲有這麼多的角落情況與CSV,我一定會錯過一些(我假設逗號作爲分隔符和"作爲引號字符(這是逃脫加倍)):

(?:   # Match either 
(?>[^",\n]*) # 0 or more characters except comma, quote or newline 
|    # or 
"   # an opening quote 
(?:   # followed by either 
    (?>[^"]*) # 0 or more non-quote characters 
|   # or 
    ""   # an escaped quote ("") 
)*   # any number of times 
"   # followed by a closing quote 
)    # End of alternation 
(?=,|$)  # Assert that the next character is a comma (or end of line) 

在VB.NET:

Dim ResultList As StringCollection = New StringCollection() 
Dim RegexObj As New Regex(
    "(?:   # Match either" & chr(10) & _ 
    " (?>[^"",\n]*) # 0 or more characters except comma, quote or newline" & chr(10) & _ 
    "|    # or" & chr(10) & _ 
    " ""   # an opening quote" & chr(10) & _ 
    " (?:   # followed by either" & chr(10) & _ 
    " (?>[^""]*) # 0 or more non-quote characters" & chr(10) & _ 
    " |    # or" & chr(10) & _ 
    " """"   # an escaped quote ("""")" & chr(10) & _ 
    ")*   # any number of times" & chr(10) & _ 
    " ""   # followed by a closing quote" & chr(10) & _ 
    ")    # End of alternation" & chr(10) & _ 
    "(?=,|$)  # Assert that the next character is a comma (or end of line)", 
    RegexOptions.Multiline Or RegexOptions.IgnorePatternWhitespace) 
Dim MatchResult As Match = RegexObj.Match(SubjectString) 
While MatchResult.Success 
    ResultList.Add(MatchResult.Value) 
    MatchResult = MatchResult.NextMatch() 
End While 
+0

謝謝Tim,我會試試看。 –

+0

\ * Noo-o-o,不是VB.NET!\ * 雖然你的答案很好。 – gaussblurinc

+0

@loldop:嘿,如果Joel Spolsky足夠好,對我來說絕對夠用:) –