Are you "greedy" or "lazy"? Uh, when you're doing your RegEx matches I mean!
Wednesday, February 11, 2009 8:51 PM
Did you know there are two types of matches you can do with RegEx? I know you can create LOADS of regex patterns, but did you know there are two different types of "matches" you can get from your LOADS of patterns? Read on for a brief description (yes, I'll keep it short I promise :>).
A friend at work (SB) was asking me about RegEx last week and man, "if you don't use it, you lose it" certainly applies here! I was soooo rusty! I think he understood the "use it or lose it" kind of thing cause he was very patient with me while we tried to work through his problem (he's smart, he figured it out on his own :>), but something struck me with one of his patterns, the concept of Greedy vs Lazy matches.
I did a bit of investigation on this before, but I wanted to refresh my memory tonight, so I figured what a great time for a new blog entry! I'm sure my friend who's in Germany right now (MP) is chocking on her schnitzel reading this geeky entry! :> Oh ya MP, you ARE addicted to your BB! :> HAHAH
It's the default type of match. It will match your expression "to the max." Say your regex is a.*b (match anything starting with 'a' followed by any number of characters, including none then finishing with a 'b'), if you have "axyzbaqwertb", that's also your match cause it satisfies the "a followed by anything ending in a b" regex.
However, what would you do if you wanted to grab the two separate parts ("axyzb" followed by the "aqwertb")? Yes, one way would be to have two regex patterns. But another way would be to use the lazy quantifier '?' after the '*' in the regex patter "a.*?b" That will find both the "axyzb" and "aqwertb"
I hope that helps to explain a bit about the difference between greedy and lazy regex.
The 30 Minute Regex Tutorial
Expresso Regular Expression Development Tool - This is a fantastic way to create/modify your regex patterns! Just like creating a 'test' or sample solution/project to test a small piece of code or API, Expresso does that for your but for your regex patterns AND your test strings/documents! It's pretty cool!