
What I Learned Today: Regular Expression Backreferences
This is another post in my challenge to learn something new every day and then share that in a blog post.
This is fairly simple, but even though I'm comfortable with regular expressions, I was not familiar with the "?:" syntax (aka: question mark colon). I was working on some Behat tests using the MinkExtension, and this is used fairly often in the code (?P<option>(?:[^"]|\\")*)
.
The ?P<option>
portion says to name the group enclosed by parenthesis "option", so in PHP in will be in the variable $option. The ?:
portion says to not capture that group enclosed by parenthesis in a backreference. Besides being an optimization for the regular expression engine, it could be helpful to use this when doing a preg_match to only extract the groups that you want.
Comments
Hey, nice post!
My reply was too long for a comment, so I made a blog-post reply instead: Check it out.
Basically, we can use the notion of a backreference to improve Behat/Mink's quoted-string pattern.
Wed, 09/11/2013 - 07:42