Try .NET RegEx

I've talked before about how convenient it is to have try.dot.net available online, and today I want to call out a specific use I've put it to a number of times: regular expressions.

Regular expressions are easy to write, somewhat harder to read, and very practical for the use case of finding substrings, extracting specific portions of text, and validation. Don't fear the syntax!

Experimenting with regular expressions

Like anything, a bit of trial and error will help you better understand the code you write and how your tools work.

When working with regular expressions, I start with some positive examples (matches I want) and negative examples (things I don't want to match, that may be interesting for some specific reason).

For example, the other day I needed to test property names to see if they matched the pattern IsFoo, commonly used in boolean variables.

I specifically didn't want to match things that didn't have that specific casing, and I wanted the "Foo" part available. Here's what I came up with.

using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Linq;

public class Program
{
  public static void Main()
  {
    var re = new System.Text.RegularExpressions.Regex("Is[A-Z]");
    Console.WriteLine(re.IsMatch("Isometric")); // false
    Console.WriteLine(re.IsMatch("IsEnabled")); // true

    re = new System.Text.RegularExpressions.Regex("Is([A-Z][A-Za-z0-9_]*)");

    var match = re.Match("Isometric");
    Console.WriteLine(match.Success);         // false

    match = re.Match("IsEnabled");
    Console.WriteLine(match.Success);         // true
    Console.WriteLine(match.Groups[0].Value); // "IsEnabled"
    Console.WriteLine(match.Groups[1].Value); // "Enabled"
  }
}

You can see that at first I focused on the matching part, and then I did a second regular expression that would help me extract the thing I cared for (captured in match.Groups[1]).

Specialized Websites

There are a handful of websites that can also help you with testing regular expressions, such as Regex Storm by Will Boyd. He also has a nice reference sheet.

PowerShell

Another useful tool for prototyping this sort of stuff is PowerShell, too.

In PowerShell, the -match operator can be used to test one string against a regular expression string.

For example, 'abc' -match 'ab.' will yield True.

After a match is made, the $Matches hashtable is populated with captured, so you can do the following (or just evaluate $Matches to see everything in it).

PS > 'abc' -match 'ab(.)'
True
PS > $Matches.0
abc
PS > $Matches.1
c

To do string replacement with regular expressions, the -replace operator is your friend.

PS > 'abc' -replace '(.)b(.)', '$1 and $2 from $&'
a and c from abc

References

Happy matching!

Tags:  dotnetpowershell

Home