2014-02-25 27 views
0

我在C#中有正则表达式的问题,我不能在一个数组中返回多个匹配。我试过用循环来做,但我觉得必须有更好的方法。在PHP中,我通常只需要做:正则表达式在数组中的多个匹配

<?php 

$text = "www.test.com/?site=www.test2.com"; 
preg_match_all("#www.(.*?).com#", $text, $results); 

print_r($results); 

?> 

将返回:

Array 
(
    [0] => Array 
     (
      [0] => www.test.com 
      [1] => www.test2.com 
     ) 

    [1] => Array 
     (
      [0] => test 
      [1] => test2 
     ) 

) 

然而,出于某种原因,我的C#代码只找到的第一个结果(测试)。这里是我的代码:

string regex = "www.test.com/?site=www.test2.com"; 
Match match = Regex.Match(regex, @"www.(.*?).com"); 

MessageBox.Show(match.Groups[0].Value); 

回答

4

您需要使用Regex.Matches而不是Match如果你想找到所有Matches返回一个MatchCollection

例如:

string regex = "www.test.com/?site=www.test2.com"; 
var matches = Regex.Matches(regex, @"www.(.*?).com"); 
foreach (var match in matches) 
{ 
    Console.WriteLine(match); 
} 

会产生这样的输出:

// www.test.com 
// www.test2.com 

如果你想所有比赛存储到Array您可以使用LINQ

var matches = matches.OfType<Match>() 
       .Select(x => x.Value) 
       .ToArray(); 

抢你的价值(testtest2)你需要Regex.Split

var values = matches.SelectMany(x => Regex.Split(x, @"www.(.*?).com")) 
      .Where(x => !string.IsNullOrWhiteSpace(x)) 
      .ToArray(); 

那么值将包含testtest2

+0

谢谢你,但我怎么能单独访问每个这些比赛的?另外,我怎样才能抓住“测试”和“测试2”,就像我对比赛一样? – user2879373

+0

@ user2879373我已经更新了我的答案。但是我认为'test'本身与您的模式不匹配。是吗? –

+0

它应该从www.test.com抓取测试,从www.test2.com抓取test2。 – user2879373