簡體   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