in reply to Using index when the substring as is a regular expression
Take a look at the pos() function, it returns the position of the end of the match. But really looks to me like you don't know about the magic variables $1 to $9, which capture your parentheses...
First some codes that does what you ask for :
$s = "Test-01-xxx"; if ($s =~ /-(\d\d)-/g) { print "Pos: $pos - ", pos( $s )-3, "\n"; }
And here's some code that does what you need :
$s = "Test-01-xxx"; if ($s =~ /(.*?)-(\d\d)-(.*)/g) { print "The string was split into :\n" print "Left part : $1\n"; print "Number part : $2\n"; print "Right part : $3\n"; }
Update : On rereading your post, I see that you want the start of a RE, so there is no way you can get around solution number two. Here's the necessary merge of method one and two. One method is to use the $& variable, which will slow your program down because Perl will keep track of every match in the $& variable then (but maybe perl does anyway, see here for more info about $&). The other method would be to introduce even more parentheses :
$s = "Test-01-xxx"; # Method 1, possibly slow if ($s =~ /-(\d\d)-/g) { print "Pos: $pos - ", pos( $s )- length( $& ), "\n"; } # Method 2, possibly slow if ($s =~ /(-(\d\d)-)/g) { print "Pos: $pos - ", pos( $s )- length( $1 ), "\n"; }
Update : See below for stephens info about @- - there's something to learn about Perl every day :-)
|
|---|