Reputation: 35374
Let's take this code snippet
var input = @"
a:1
b:22
a:3
b:44
";
var pattern = @"b:([^\n]+)\n";
var match = Regex.Match(input, pattern);
And the result I get in match is at the below snapshot.
How can we get the list of values of b
e.g. {22, 44}?
I can only see the 22.
Upvotes: 3
Views: 106
Reputation: 43023
Instead of Match
, use Matches
method to get multiple matches in one go:
var matches = Regex.Matches(input, pattern);
for (int i = 0; i < matches.Count; i++ )
{
var value = matches[i].Value;
}
or using foreach
syntax:
foreach (Match match in matches)
{
var value = match.Value;
}
Upvotes: 6
Reputation: 21337
Use Regex.Matches
method instead of Regex.Match
. Here's an example from MSDN
string pattern = "a*";
string input = "abaabb";
foreach (Match m in Regex.Matches(input, pattern))
Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
if you want a list of matched values
Regex.Matches(input, pattern).Select(m => m.Value).ToList();
Upvotes: 5
Reputation: 13338
Returns a new Match object with the results for the next match, starting at the position at which the last match ended (at the character after the last matched character).
What could be even easier, is to just loop through all Matches
.
Upvotes: 2