Reputation: 51064
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.
Upvotes: 1
Views: 1250
Reputation: 3670
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");
}
}
Upvotes: 1
Reputation: 19604
That has nothing to do with inverting the Regexp. Just search for the relevant Text and put it in a group.
Upvotes: 2