[Solved] How to get multiple regex matches c#


With the risk of summoning all sorts of foul creatures (and I’m not mainly referring to SO users), here’s a little unit test for you:

[TestMethod]
public void RegexTest()
{
    var input = "<th>192.168.1.1</th>\r<th>443</th>";

    var regex = @"(?s)<th>([0-9\.]*?)</th>.*?<th>([0-9]*?)</th>";
    var matches = Regex.Matches(input, regex);

    foreach (Match match in matches)
        Console.WriteLine("IP: {0}, port: {1}", match.Groups[1].Value, match.Groups[2].Value);
}

The problem is, which is one of the reasons you should generally avoid using regexes to parse HTML, that the exact formatting of the input becomes very important. For instance the above test breaks if you instead would have <th> 443</th> in the input.

Now go get your stake and your silver bullets, they’re coming for us!!

solved How to get multiple regex matches c#