Extract multiple items using one regular expression in C#

.NET programming topics
Post Reply
Cyclops
Lieutenant
Lieutenant
Posts: 71
Joined: Wed Jul 15, 2009 1:48 pm
Location: London

Extract multiple items using one regular expression in C#

Post by Cyclops » Thu Dec 31, 2009 9:47 am

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}"));
Post Reply

Return to “.NET Programming”