tags:

views:

680

answers:

4

How would I invert .NET regex matches? I want to extract only the matched text, e.g. I want to extract all IMG tags from an HTML file, but only the image tags.

A: 

Can you give an example?

Do you want to the "src" data... or, everything between the tags?

Nescio
+2  A: 

That has nothing to do with inverting the Regexp. Just search for the relevant Text and put it in a group.

VVS
A: 

Not sure what you mean. Are you talking about capturing groups?

aku
+1  A: 

I'm with David H.: Inversion would imply you don't want the matches, but rather the text surrounding the matches, in which case the Regex method Split() would work. Here's what I mean:

static void Main(string[] args)
{
    Regex re = new Regex(@"\sthe\s", RegexOptions.IgnoreCase);

    string text = "this is the text that the regex will use to process the answer";

    MatchCollection matches = re.Matches(text);
    foreach(Match m in matches)
    {
        Console.Write(m);
        Console.Write("\t");
    }

    Console.WriteLine();

    string[] split = re.Split(text);
    foreach (string s in split)
    {
        Console.Write(s);
        Console.Write("\t");
    }
}
ZeroBugBounce