Reputation: 73
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);
Upvotes: 0
Views: 1505
Reputation: 101681
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
Upvotes: 4