Showing posts with label Regular Expressions. Show all posts
Showing posts with label Regular Expressions. Show all posts

Monday, July 21, 2008

Free Tools for Testing Regular Expressions

Creating and maintaining regular expressions are not like riding a bike. You can create a regular expression for a project and come back a couple months later and it is unreadable. Scott Hanselman has a saying, "If you try to solve a problem with a regular expression, you now have two problems."

Fortunately there are several resources available for free to help you test and understand regular expressions.

The Kellerman Quick Reference Pack that contains a Regular Expression cheat sheet:
Free Quick Reference Pack

If you work at a bank and can't install software use Reggie. This is a regular expression tester, and reference in a simple HTML file. This is my favorite.
Reggie

If you are just getting started with Regular Expressions, Roy Osherove has a great free tool called Regulazy that will help you build simple Regular Expressions.
Regulazy

Roy also has an advanced tool (also free) called Regulator for building regular expressions.
Regulator

Someone may have already built the regular expression you need. Take a look at this giant repository of regular expressions.
RegexLib

Tuesday, July 8, 2008

Regular Expression Groups in .NET

Regular Expressions are a great way of querying and replacing text. A while ago I stumbled upon a feature in the .NET framework for regular expressions: groups. Groups are not supported in browsers but they can be used for back end code in .NET. Breaking expressions into groups makes it easier to parse text. Here is a line of text from a standard FTP directory listing:

string directoryLine= "drwxr-xr-- dds grp 0 Feb 23 2002 data";

Here is the regular expression that we can use to parse the FTP directory line:

string mask = @"^(?<dir>[\-d])(?<permission>([\-rwxt]+))\s+\d+\s+\w+\s+\w+\s+(?<size>\d+)\s+(?<timestamp>\w+\s+\d+\s+\d{1,2}:\d{2})\s+(?<name>.+)"

The group names are prefixed by a question mark and then the group name in <name>.

Some example code to pull out the groups:

Regex regEx = new Regex(mask);
Match match = regEx.Match(directoryLine);

if (match.Success)
{
string fileName= match.Groups["name"].Value;

if (match.Groups["dir"].Value == "d")
{
//Do Something
}
}