The importance of regular expressions - pt 1

Monday, 30 June 2008


Sometimes when asked by a junior developer the cleanest way to solve a problem, if the answer is 'regular expressions' this is usually followed by a groan or a sigh or a combination of both.

The truth is if you can learn how to handle regular expressions early on you will have one of the most simplest, cleanest and efficient tools in your arsenal to take on a variety of problems.

The reason regular expressions are so useful is that they can be used to target what you need in any string with the flexibility of being able to use your matches to process the given string.

php has a variety of powereful functions that can be used in conjunction with regular expressions, but before I go in to that I want to point out some of the best places to find out about regular expression so you can start learning and practicing.

To get your head around the basics it's best to try and track down somewhere that explains regular expressions in detail, I don't want to go in to that here as there are 100's of pages about this already. The place I recommend looking at is here, which explains clearly from a php perspective how regular expressions work. This is a great site for new beginners and for anyone who wants to check-up rules when you're getting stuck.

So once you've had a play around with a few basic expressions and you're still banging your head on the table and everyone is looking the other way when you cry out "who can help me with my regex!", don't panic, there is help! What you're going to want is one of these a regular expression tester. This has saved me many a time when something isn't matching or it's matching too much or too little. You can simply plug in your expression and it will show you exactly where it's matching and you can tweek your expression quickly without having to commit your changes to a repository etc.

Hopefully this is enough to get you started. As everyone knows practice makes perfect, which is the same with regular expressions. Hopefully with your cheat sheet and regular expression checker it will help you avoid most simple headaches. In my next post I will look at some useful php functions to help deal with processing regular expressions.
blog comments powered by Disqus