简体   繁体   中英

Regex multiple matches in array

I have this problem with Regex in C#, where I can't return multiple matches in one array. I've tried using a loop to do it, but I feel there has to be a better way. In PHP, I usually just have to do:

<?php

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

 print_r($results);

 ?>

Which will return:

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

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

 )

However, for some reason, my C# code only finds the first result (test). Here is my code:

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

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

You need to use Regex.Matches instead of Match which returns a MatchCollection , if you want to find all Matches .

For example:

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

Will produce this output:

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

If you want to store all matches into an Array you can use LINQ :

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

To grab your values ( test and test2 ) you need Regex.Split :

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

Then values will contain test and test2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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