Page 1 of 1

Extract multiple items using one regular expression in C#

Posted: Thu Dec 31, 2009 9:47 am
by Cyclops
First, create a regular expression with named patterns, for example, IPAddr, Day, etc. The Discard named pattern names items that are not used.

Then use the Match Result method to extract the item corresponding to the named pattern.

Code: Select all

String Pattern = @"(?[\S]+)(?[\s-\[]*)(?\d{1,2})(?/)(?[a-zA-Z]+)(?/)(?\d{2,4})(?:)(?\d{1,2})(?:)(?\d{1,2})(?:)(?\d{1,2})(?[\s]*)(?[\+\-]*\d{2})(?\d{2})(?([\]\s])*""(GET|HEAD)([\s])*)(?[\S]*)(?[^""]*""[\s]*)(?[0-9]*)(?[\s]*)(?([0-9])*)(?[^""]*"")(?[^""]*)(?[^""]*""[^""]*"")(?[^""]*)";

Regex RE = new Regex(Pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
...
String Line = SR.ReadLine().Trim();
...
Match M = RE.Match(Line);

Item.IPAddress = M.Result("${IPAddr}");
int Day = Int32.Parse(M.Result("${Day}"));