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 = @"(?[\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);
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

How to decompile Java code with JetBrains IntelliJ IDEA (2018.2.3, Windows 10)October 5, 2018
Java Programming Tip: SWT Photo Frame ProgramOctober 31, 2016
Vault 3 (Desktop) Version 1.63 ReleasedSeptember 9, 2016
"Compliance with Court Orders Act of 2016"April 9, 2016
Disable "Visual Voicemail" on Android / T-MobileJanuary 17, 2016
IPv6 HumorDecember 10, 2015
Java Programming Tip: Specify the JVM time zoneDecember 7, 2015