Skip to content

Instantly share code, notes, and snippets.

@perl2ruby
Created September 24, 2010 21:50
Show Gist options
  • Save perl2ruby/596113 to your computer and use it in GitHub Desktop.
Save perl2ruby/596113 to your computer and use it in GitHub Desktop.
// 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