Saturday, May 05, 2007

Maintainable Regular Expressions

We all know regular expression is a very powerful tool. But one of the difficulties we face is reading regex statements written by others. Sometimes it's almost impossible. So it's always better to document your regular expressions and make them more readable for others and make your piece of code more maintainable. Here what you can do

Regex regex = new Regex(@"
^ # anchor at the start
(?=.*\d) # must contain at least one numeric character
(?=.*[a-z]) # must contain one lowercase character
(?=.*[A-Z]) # must contain one uppercase character
.{8,10} # From 8 to 10 characters in length
\s # allows a space
$ # anchor at the end",
RegexOptions.IgnorePatternWhitespace);

You can comment your expressions using # but make sure you use the RegexOption IgnorePatternWhitespace.

1 comment:

Anonymous said...

Hey, I can't view your site properly within Opera, I actually hope you look into fixing this.