Friday, March 19, 2010

Learning Regular Expressions

During the course of your automated test efforts, you'll come across regular expressions. Regular expressions are an extremely powerful tool, but they're daunting when you're first learning them. I mean, really, can you just look at this line of code and tell me what it does?
re = /^((4\d{3})|(5[1-5]\d{2}))[ -]?(\d{4}[ -]?){3}$|^(3[4,7]\d{2})[ -]?\d{6}[ -]?\d{5}$/;
The above regular expression is used to verify that a credit card number is valid. (This is also a great example of why you should comment your code.) Such an expression is very useful, but how the heck do you write these things?

Fortunately the good folks over at Regular-Expressions.info have put together a great tutorial that explains regular expressions in detail. You'll learn what regular expressions are good for and how to write them. This is an extremely useful skill for an automator. You can perform more robust verifications with your tests, and you can use them to do other tasks like pull particular strings out of log files, or ensure email addresses are properly formatted.

It's also handy to have a tool that you can use to verify your expressions are working properly. For that, I recommend Roy Osherove's Regulator. It's free, and allows you to test your regular expression against a variety of inputs, allowing you to make sure you'll correctly match the patterns you're expecting.

Happy Automating!

1 comment:

  1. I second that.
    http://www.regular-expressions.info/tutorial.html is an awesome website :)

    RegExs can be daunting to get using but they're in the very-clever area of a testers toolbox.

    Mark.

    ReplyDelete