Eric Bergman-Terrell's Blog

.NET Programming Tip: How to Extract Multiple Items Using One Regular Expression
October 4, 2010

To extract multiple items from text using a single regular expression, create a regular expression with named patterns, for example, IPAddr, Day, etc. (see below). The Discard named pattern specifies items that are not used. Then use the Regex Match property to extract the item corresponding to the named pattern from the results:

String Pattern = @"(?<IPAddr>[\S]+)(?<Discard>[\s-\[]*)(?<Day>\d{1,2})(?<Discard>/)(?<Month>[a-zA-Z]+)(?<Discard>/)(?<Year>\d{2,4})(?<Discard>:)(?<Hour>\d{1,2})(?<Discard>:)(?<Minute>\d{1,2})(?<Discard>:)(?<Second>\d{1,2})(?<Discard>[\s]*)(?<TZInt>[\+\-]*\d{2})(?<TZFrac>\d{2})(?<Discard>([\]\s])*""(GET|HEAD)([\s])*)(?<File>[\S]*)(?<Discard>[^""]*""[\s]*)(?<Status>[0-9]*)(?<Discard>[\s]*)(?<Bytes>([0-9])*)(?<Discard>[^""]*"")(?<RefURL>[^""]*)(?<Discard>[^""]*""[^""]*"")(?<UserAgent>[^""]*)";
Regex RE = new Regex(Pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
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}"));
Keywords: Regular Expression, Match Multiple Text Patterns, Regex

Reader Comments

Comment on this Blog Post

Recent Posts

TitleDate
Get JetBrains IDEs to Remember Subversion (SVN) CredentialsNovember 3, 2026
Converting a Thinkpad from Windows 11 to Linux MintOctober 29, 2026
Raspberry Pi Camera Trap and Animal Detection ProgramAugust 29, 2026
Python Tip: Fix Incorrect Orientation of Digital PhotosAugust 8, 2026
EBT Weather is now available for Windows and LinuxMay 30, 2026
Node.js + Express: How to Block Requests by User-Agent HeadersJanuary 7, 2026
Vault 3 is Now Available for Windows on ARM Machines!December 13, 2025