
pagod
New User
Sep 21, 2007, 2:04 AM
Post #1 of 1
(1158 views)
|
|
matching using backref as hash index in regex
|
Can't Post
|
|
hi, i'm trying to match lines where parts of the regular expression depend on what's been found earlier: i have some values that may or may not be enclosed in quotes; if there are quotes, then the values may contain anything but the quotes themselves, if not then they may only contain a limited set of characters. in order to do that, i wanted to use the following code (snipplet):
use strict; my %allowed = ( "" => "[\w\.\-]", "\"" => "[^\"]", "\'" => "[^\']" ); my @lines = ( "id=\"abc\"", # expected: abc "id=\'abc\'", # expected: abc "id=\"abc def\"", # expected: abc def "id=abc", # expected: abc "id=abc def", # expected: abc ); foreach my $line ( @lines ) { print $line; if( $line =~ /\w=([\'\"]?)($allowed{\1}*)\1(.*)$/ ) { print " => $2/$3\n"; } else { print " didn't match\n"; } } i expected the value of the first parenthesized expression ([\'\"]?) to be used to retrieve and insert the collection of allowed characters, but when i run perl it tells me: pagod> perl test.pl Quantifier follows nothing in regex; marked by <-- HERE in m/\w=(['"]?)(* <-- HERE )\1(.*)$/ at test.pl line 18. id="abc" i've tried to put the '*' in the values in the hashtable, but then $2 is always empty :-\ i thought i'd be able to use the backref as a key in for my hashtable, but somehow it doesn't work that way... or have i done anything wrong? any idea how i could do that? thx in advance! Pagod
|