Tuesday, April 7, 2009

Regex Examples

code is copied from
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy

Publisher: Sybex;
ISBN: 0782129110
*/

Notice how to use Match, Group, Capture, MatchCollection.


using System;
using System.Text.RegularExpressions;

namespace GroupCapture
{
class Program
{
static void Main(string[] args)
{
// create a string containing area codes and phone numbers
string text =
"(800) 555-1211\n" +
"(212) 555-1212\n" +
"(506) 555-1213\n" +
"(650) 555-1214\n" +
"(888) 555-1215\n";

// create a string containing a regular expression to
// match an area code; this is a group of three numbers within
// parentheses, e.g. (800)
// this group is named "areaCodeGroup"
string areaCodeRegExp = @"(?\(\d\d\d\))";

// create a string containing a regular expression to
// match a phone number; this is a group of seven numbers
// with a hyphen after the first three numbers, e.g. 555-1212
// this group is named "phoneGroup"
string phoneRegExp = @"(?\d\d\d\-\d\d\d\d)";

// create a MatchCollection object to store the matches
MatchCollection myMatchCollection =
Regex.Matches(text, areaCodeRegExp + " " + phoneRegExp);

// use a foreach loop to iterate over the Match objects in
// the MatchCollection object
foreach (Match myMatch in myMatchCollection)
{

// display the "areaCodeGroup" group match directly
Console.WriteLine("Area code = " + myMatch.Groups["areaCodeGroup"]);

// display the "phoneGroup" group match directly
Console.WriteLine("Phone = " + myMatch.Groups["phoneGroup"]);

// use a foreach loop to iterate over the Group objects in
// myMatch.Group
foreach (Group myGroup in myMatch.Groups)
{

// use a foreach loop to iterate over the Capture objects in
// myGroup.Captures
foreach (Capture myCapture in myGroup.Captures)
{
Console.WriteLine("myCapture.Value = " + myCapture.Value);
}

}

}
}
}
}

Another Exmple is you are writing an application to process data contained in a text form.Each file contains information about a single customer.
First Name:Tom
Last Name: Perham
Address: 1 Pine St.
City: Springfield
Zip: 01332

After reading the data into a string variable s:


string p=@"First Name: (?.*$)\n"+
@"Last Name: (?.*$)\n"+
@"Address: (?
.*$)\n"+
@"City: (?.*$)\n"+
@"Zip: (?.*$)\n";
Match m=Regex.Match(s,p,RegexOptions.Mutiline);
string fullName=m.Groups["firstName"]+" "+m.Groups["lastName"];
string zip=m.Groups["zip"].ToString();

Note we need to specify the Mutiline option.

No comments: