Tuesday, May 15, 2007

Regular Expressions in .NET

There are powerful tools in Unix such as grep, sed etc. These programs make use of regular expressions - regexp. Luckily, .NET contains a very useful class - a Regex class in a System.Text.RegularExpressions namespace.

Before using of regular expressions you need to understand the syntax. Here is a basic:














.Matches any single character
^Matches the beginning of a string
$Matches the end of a string
*Matches the preceding character or subexpression zero or
more times
+Matches the preceding character or subexpression one or
more times
( )subexpression

For more information about regular expressions syntax see this link

Now I can show how it is being used. The key method is Regex.IsMatch():

Regex regex = new Regex("^a...b$");

bool test1 = regex.IsMatch("axyzb");    //true

bool test2 = regex.IsMatch("axyzxyzb"); //false

bool test3 = regex.IsMatch("d");        //false



The following example validates an e-mail adress:

using System.Text.RegularExpressions;

 

class EmailAdress

{

  static Regex emailRegex = new Regex( @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");

  public static bool Validate(string email)

  {

    return emailRegex.IsMatch(email);

  }

}



For more information see:

.NET Framework Regular Expressions (MSDN)
System.Text.RegularExpressions Namespace (MSDN)

kick it on DotNetKicks.com

No comments: