Sunday, July 13, 2008

[.NET] How to Validate strings with Regular Expressions

Hi fellas,

a tiny code-snippet to show how to use regular expressions to validate strings in .NET:

//include this
using System.Text.RegularExpressions;
string myRegEx = @"^ScuffiaIsOneBigFatFaggot$";
string myStringToValidate;
//fill string to validate from input or whatever
if (Regex.IsMatch(myRegEx, myStringToValidate))
Console.WriteLine("String is valid!");
Console.WriteLine("String is rubbish");

It's worth to underline that Regular expressions are case-sensitive, even in VB. I hate writing Regular Expressions, but Scuffia is pretty good at it so when I can't find stuff on google I always bug him when I need to validate some data. For example a couple of weeks ago I needed to validate an email and I asked him for help.
He sent this regular expression straightaway:


Writing regular expressions is a mess but reading one if someone else wrote it is definitely something you don't wanna even think about: gotta have blind faith sometimes in this job - just remember to throw some bones to them SQA people (they're paid to break what us developers put together after all).

Thanx Scuffia, the email validation reg ex is working pretty well.

No comments: