2010-05-28 19 views
1

我有一個關於.NET正則表達式的問題以及它如何定義匹配。 我寫:.NET正則表達式 - 更短的匹配

var regex = new Regex("<tr><td>1</td><td>(.+)</td><td>(.+)</td>"); 
if (regex.IsMatch(str)) 
{ 
    var groups = regex.Match(str).Groups; 
    var matches = new List<string>(); 
    for (int i = 1; i < groups.Count; i++) 
     matches.Add(groups[i].Value); 

    return matches; 
} 

我想要的是得到以下兩個標籤的內容。相反,它返回:

[0]: Cell 1</td><td>Cell 2</td>... 
[1]: Last row of the table 

爲什麼第一場比賽以</TD >和字符串的其餘部分,而不是在</TD >停止?

+0

順便說一句,強制性警告:http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags#1732454 – cHao 2010-05-28 03:35:27

回答

3

你的正則表達式包括

(.+) 

其是貪婪匹配。貪婪的匹配延伸爲遠的,因爲它們可以在匹配下一個字符(在您的案例中爲<)之前。嘗試:

(.+?) 

這是延伸爲儘可能的下一個字符匹配之前非貪婪比賽。

1

您需要指定延遲匹配。而不是+,使用+?來說,儘可能少的字符應該匹配。