Sunday, August 22, 2010

Rex–Regular Expression Exploration

samplesfa

Rex – is an MSR released tool that generates strings based on a regex expression. It’s a great tool for generating input for unit tests as well as output data for mocks. It is also makes it really easy to determine what that complex regex that you downloaded from the internet does or if the regex that you wrote really works or not.

One thing to know is that when you run the tool and if you see output with “\u”, then the tool is outputting unicode data. In this case, just add the /e:ASCII option to the command line to get plan text output.

Apart from the tool being a command line tool, another way you can use Rex is to actually reference it in your code (Visual Studio allows you to reference .exe file – not just .dll files). By doing this, you can use Rex to generate random strings that you can use for mocking or for unit test inputs. (AWESOME!)

Here is some sample code (C#) to generate random phone numbers:

using Rex;

RexSettings settings = new RexSettings(@"^\d{3}-\d{3}-\d{4}$");
settings.k = 10;
settings.encoding = CharacterEncoding.ASCII;
settings.seed = (int)DateTime.Now.Ticks;

var results = RexEngine.GenerateMembers(settings);
foreach (var result in results)
{
Console.WriteLine(result);
}

And here is the output for one run:

312-889-8953
999-741-0638
999-896-9342
898-795-0789
496-589-9259
897-910-1576
899-968-9169
846-098-3822
282-169-8069
883-898-2237

More Info:

Rex on MSR: http://research.microsoft.com/en-us/projects/rex/

Rex on the Web (Pex for Fun): http://www.pexforfun.com/Default.aspx?language=CSharp&sample=RegularExpressions

Pex and Moles for Visual Studio: http://research.microsoft.com/en-us/projects/pex/downloads.aspx (white-box testing tool that uses Rex)

Regular Expression Language Reference: http://msdn.microsoft.com/en-us/library/az24scfc.aspx

No comments: