Monday, February 23, 2009

Anonymous Types and Regular Expressions

Regular Expressions are great, and they aren't bad to program, but . It is "non-obvious" which field you are supposed to use. A group is a capture, and has captures, so where is your named capture group to get that simple piece of text?

In the spirit of the "pit of success" here's a quick way to use Regex in your program and you only have to remember one call. We'll do this by casting to an anonymous type. It looks a tad wierd, but it is super easy to use. Super easy, the second time.


using System;
using RegularExpressions;

namespace egrep
{

class egrep
{
static void Main(string[] args)
{
string text = "The the quick brown fox fox jumped over the lazy dog dog.";

var matches = Regex.grep(text, @"\b(?<double_word>\w+)\s+(\k<double_word>)\b",
new { double_word = "" });

foreach (var find in matches)
Console.WriteLine(find.double_word);
}
}
}