0

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

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, but how can I access each of these matches separately? Also, how can I grab just "test" and "test2", like I did with match?
@user2879373 I have updated my answer.But I think test itself doesn't match with your pattern.does it?
It should be grabbing test from www.test.com and test2 from www.test2.com.
@user2879373 I understand, you need Regex.Split for that see my update again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.