Tuesday, July 1, 2008

Regular Expression Groups

Regular Expression Groups

===========
Sample Code
===========
string testIpString = "192.168.110.112";
string regularExpressionString = @"^(?<octet1>[01]?\d\d2[0-4]\d25[0-5])(\.)(?<octet2>[01]?\d\d2[0-4]\d25[0-5])(\.)(?<octet3>[01]?\d\d2[0-4]\d25[0-5])(\.)(?<octet4>[01]?\d\d2[0-4]\d25[0-5])$";

//Option 1//Match matches = Regex.Match(testIpString, regularExpressionString);
//Option 2//Match matches = Regex.Match(testIpString, regularExpressionString,RegexOptions.ExplicitCapture);

Console.WriteLine("Groups");

foreach (Group group in matches.Groups)
{
Console.WriteLine(group.ToString());
}

Console.WriteLine("Named Groups");

Console.WriteLine( matches.Groups["octet1"].ToString());
Console.WriteLine( matches.Groups["octet2"].ToString());
Console.WriteLine( matches.Groups["octet3"].ToString());
Console.WriteLine( matches.Groups["octet4"].ToString());

Console.ReadLine();
===============
Option 1 output
===============
Groups
192.168.110.112
.
.
.
192
168
110
112
Named Groups
192
168
110
112
===============
Option 2 output
===============
Groups
192.168.110.112
192
168
110
112
Named Groups
192
168
110
112
===============
Commentary
===============

Most of the power is in the regular expression:

@"^(?<octet1>[01]?\d\d2[0-4]\d25[0-5])(\.)(?<octet2>[01]?\d\d2[0-4]\d25[0-5])(\.)(?<octet3>[01]?\d\d2[0-4]\d25[0-5])(\.)(?<octet4>[01]?\d\d2[0-4]\d25[0-5])$";

No comments: