Sunday, April 19, 2009

JavaScript Regex with group captures

I'm pretty familiar with regular expressions in Perl, but I couldn't remember how to capture regex matches in JavaScript. I searched for javascript regex, and found this page: Regular Expressions in JavaScript | evolt.org

In it, I found this paragraph:
String.match(pattern)
var str = "Watch out for the rock!".match(/r?or?/g)
str then contains ["o","or","ro"]

This wasn't exactly what I wanted because I wanted capture parenthesis. I opened up Firebug and entered these 2 lines (And yes, there are more efficient ways to parse out dates, I'm just using this as an example):
>>> var testArray = "2009-01-01".match(/(\d{4})-(\d{2})-(\d{2})/)
>>> testArray
["2009-01-01", "2009", "01", "01"]
This showed me that my variable testArray will hold the full match (without my matching groups), and then each capture group in the rest of the elements in the array.

I think the equivalent of this in Perl is something like this (although I don't have Perl handy to test this):

my $date='2009-01-01';
my @testArray;
if ( $date =~
/(\d{4})-(\d{2})-(\d{2})/ ) {
@testArray = ($&, $1, $2, $3);
}
I could have just assigned @testArray to the outcome of the regex match, but Perl doesn't put the full match into that array. The $& variable in Perl contains the entire matched string.

No comments:

Post a Comment