2014-02-25 29 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