Testing Regular Expressions with Regex Builder

I have been working on a recent project where I need to make heavy use ofregular expressions and I have been spending a lot of time tweaking theseexpressions. Well, the tweaking is a lot easier if you can use a visual tool totest the expressions. There are lots of such tools out there, and I provide ashort list below, but I decided to hack together my own tool just to learn howthese things work under the hood.

This is a very simple tool written in CSharp to visually highlight regularexpression matches. The source is available on github and it's called RegexBuilder (I know... very original name).

Regex Builder

Here's how it works... There are 2 text boxes, one for the regular expressionitself and another for the test string and a couple of check boxes for theoptions. I run the regular expression provided with options against the teststring and I receive back a collection of matches. I also have a Style classthat encapsulates two Colors for background and foreground. I then loopthrought the match collection and I apply the alternating Style to each Matchin the collection. The highlighting is made possible by the properties of the rich text box. This is the core of the code:

string regexPattern = textRegex.Text;
string inputText = rtbTest.Text;
int i = 0;
RegexOptions ro = new RegexOptions();

if (!checkCase.Checked)
    ro = ro | RegexOptions.IgnoreCase;

if (checkMultiLine.Checked)
    ro = ro | RegexOptions.Multiline;

regex = new Regex(regexPattern, ro);
matches = regex.Matches(inputText);

foreach (Match m in matches) {
    Style s = getStyle(i);
    rtbTest.SelectionStart = m.Index;
    rtbTest.SelectionLength = m.Length;
    rtbTest.SelectionColor = s.ForegroundColor;
    rtbTest.SelectionBackColor = s.BackgroundColor;
    rtbTest.Select(m.Index + m.Length, 0);

    i++;
}

Regex Builder was a simple mental exercise around regular expressions for meand it's the minimum thing that actually works. I have no plans to develop itfurther. There are other tools that fall in this Regex Tester/Debugger category and are able to accomplish much more than my humble Regex Builder:

Comments

Comments powered by Disqus