2012-08-01 57 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

两者我知道这是一个老问题,但我在这里结束了通过搜索确认我自己的想法,也没有明确的答案。