Trey Balut Trey Balut - 1 month ago 15
C# Question

Regex Match Collection multiple matches

I'm trying to retrieve all text between

<td>
and
</td>
, but I only get the first match in my collection. Do I need a
*
or something? Here is my code.

string input = @"<tr class=""row0""><td>09/08/2013</td><td><a href=""/teams/nfl/new-england-patriots/results"">New England Patriots</a></td><td><a href=""/boxscore/2013090803"">L, 23-21</a></td><td align=""center"">0-1-0</td><td align=""right"">65,519</td></tr>";

string pattern = @"(?<=<td>)[^>]*(?=</td>)";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches)
{
try
{
listBoxControl1.Items.Add(matches.ToString());
}
catch { }
}

Answer

Use the following regex expression:

string input = "<tr class=\"row0\"><td>09/08/2013</td><td><a href=\"/teams/nfl/new-england-patriots/results\">New England Patriots</a></td><td><a href=\"/boxscore/2013090803\">L, 23-21</a></td><td align=\"center\">0-1-0</td><td align=\"right\">65,519</td></tr>";

string pattern = "(<td>)(?<td_inner>.*?)(</td>)";

MatchCollection matches = Regex.Matches(input, pattern);

foreach (Match match in matches) {
    try {
        Console.WriteLine(match.Groups["td_inner"].Value);
    }
    catch { }
}
Comments