正则表达式中的多个匹配

时间:2014-02-25 22:35:31

标签: c# regex

我在C#中使用Regex时出现此问题,我无法在一个数组中返回多个匹配项。我尝试过使用循环来做到这一点,但我觉得必须有更好的方法。在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);

1 个答案:

答案 0 :(得分:4)

如果您想查找所有Match,则需要使用Regex.Matches代替MatchCollection,而Matches会返回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();

test

要获取您的值test2var values = matches.SelectMany(x => Regex.Split(x, @"www.(.*?).com")) .Where(x => !string.IsNullOrWhiteSpace(x)) .ToArray(); ),您需要Regex.Split

test

然后,值将包含test2和{{1}}