Created
September 24, 2010 21:50
-
-
Save perl2ruby/596113 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Dealing with named grouping in regular expressions in .net | |
using System; | |
using System.Text.RegularExpressions; | |
using System.Collections; | |
public class RegexEg1 | |
{ | |
static public void Main () | |
{ | |
string[] words = new string[] { | |
"Tom,32,Denver,tom1", | |
"Jill,27,New York,jill", | |
"Bill,49,12345,bill1", | |
"John,22,Phoenix,john", | |
"Tom,73,Albany,tom2", | |
}; | |
string pattern = @"^(?<firstname>[A-Za-z]+),(?<age>\d+),(?<city>[a-zA-Z]+( [a-zA-Z]+)?),(?<userid>\w+)$"; | |
Regex regex = new Regex(pattern); | |
foreach (string word in words) | |
{ | |
Boolean is_match = false; | |
foreach (Match m in regex.Matches(word)) | |
{ | |
is_match = true; | |
Console.WriteLine("matched: " + word + " (" + | |
"firstname=" + m.Groups["firstname"].Value + ", " + | |
"age=" + m.Groups["age"].Value + ", " + | |
"city=" + m.Groups["city"].Value + ", " + | |
"userid=" + m.Groups["userid"].Value + | |
")" ); | |
} | |
if (!is_match) | |
{ | |
Console.WriteLine("UNMATCHED: " + word); | |
} | |
} | |
} | |
} | |
Output: | |
matched: Tom,32,Denver,tom1 (firstname=Tom, age=32, city=Denver, userid=tom1) | |
matched: Jill,27,New York,jill (firstname=Jill, age=27, city=New York, userid=jill) | |
UNMATCHED: Bill,49,12345,bill1 | |
matched: John,22,Phoenix,john (firstname=John, age=22, city=Phoenix, userid=john) | |
matched: Tom,73,Albany,tom2 (firstname=Tom, age=73, city=Albany, userid=tom2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment