繁体   English   中英

正则表达式数组中的多个匹配项

[英]Regex multiple matches in array

我在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);

您需要使用Regex.Matches而不是Match ,它返回一个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();

要获取您的值( testtest2 ),您需要Regex.Split

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

然后值将包含testtest2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM