My First Regular Expression

Published on 27th May, 2014

It took a few years. But I finally gave in and started the process of learning regular expressions. It's confusing to say the least.

BUT, putting in the time is well worth the effort. The need to match a pattern comes up so frequently that, as a developer, you should always have this knowledge your toolbox. A co-worker made the point that, yes, it does take some time to learn, but the time you'll save is unquestionably worth it.

I needed to parse out any string that looked like this from a log file that my application was generating:

conversion_failed|123456

Essentially it's an error description and a database record ID. So after only a few minutes I'd whipped up the following:

/([A-z,_]+)|([0-9]{6,})/

That works! Of course I'm using PHP so your actual implementation may vary but that pulled out the strings I needed. Let me break it down a bit

[A-z,_]+

This matches any number(the plus sign)of letters, and underscores. I enclosed this in parenthesis to indicate that I wanted to capture it as a group.

Next is just a pipe | which is a literal in this case. I know from writing the logging script that the pipe will always be there.

Lastly it's:

[0-9]{6,}
This matches any combination of 6 numbers. Again, I know that the ID will always be 6 integers, so I can safely do that. If the ID could be any number of numbers, I would replace "{6,}" with "+"

Take the time to learn when you get a chance. You'll never regret the time you spend. If you need a bit of assistance, this site has a fantastic little guide and GUI: http://rubular.com/

Richard

This article is my 24th oldest. It is 280 words long

comments powered by Disqus