2012-08-01 56 views
1

來自perl,我有點困惑的asp.net正則表達式類。如何從asp.net regex.match中提取結果?

我有一個簡單的模式,我想匹配:「數字文本號」

我的代碼如下所示:

 Match results = Regex.Match(mystring, @"(\d+)\s+(Highway|Hwy|Route|Rte)\s+(\d+)",RegexOptions.IgnoreCase); 

    foreach (Group g in results.Groups) 
    { 
     string token = g.Value; 
    } 

的問題是,該組似乎包含4個結果,不我期望的3 - 第一個是匹配的整個字符串,而接下來的3個是我期望的。

有沒有簡單的方法來直接訪問我的3個結果?

回答

0
var results = Regex.Match("55 Hwy 66", @"(\d+)\s+(Highway|Hwy|Route|Rte)\s+(\d+)", RegexOptions.IgnoreCase).Groups.OfType<Group>().Select((name, index) => new {name, index}).Where(x => x.index > 0).Select(x => x.name).ToList(); 
+0

這並不排除包含完整匹配的項目 - 我仍然在結果中獲得4個項目。 – chris 2012-08-01 15:15:14

+0

已更新........ – 2012-08-01 16:19:11

0

你可以使用Matches

// Define a test string.   
string text = "The the quick brown fox fox jumped over the lazy dog dog."; 

// Find matches. 
MatchCollection matches = rx.Matches(text); 

// Report the number of matches found. 
Console.WriteLine("{0} matches found in:\n {1}", 
         matches.Count, 
         text); 

// Report on each match. 
foreach (Match match in matches) 
{ 
    ... 
} 
+0

這只是在包含相同4組的MatchCollection中返回一個Match。 – chris 2012-08-01 15:19:28

0

這只是它是如何設計工作的情況,它只是忽略了第一場比賽的情況下。我同意這是一個奇怪的實現,而不是我預期它會如何工作。

如果正則表達式引擎可以找到匹配項,則由Groups屬性返回的GroupCollection對象的第一個元素包含一個匹配整個正則表達式模式的字符串。

here

兩者我知道這是一個老問題,但我在這裏結束了通過搜索確認我自己的想法,也沒有明確的答案。