Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Answer: How do I retrieve the position of the first occurrence of a match?

( #642691=categorized answer: print w/ replies, xml ) Need Help??

Q&A > regular expressions > How do I retrieve the position of the first occurrence of a match? contributed by lima1

$line =~ m{(\d+)}g; my $pos = pos($line) - length $1;
When using the g modifier, pos($line) returns the offset where the last m{}g search left off for $line. In other words it points to the position AFTER the last match. So to get the position of the match, one has to substract the length of the match.

Another possibility is using the match variable $` ($PREMATCH).

$line =~ m{\d+}; my $pos = length $`;
This solution can be slightly faster, but match variables slow all other regular expressions without capturing parentheses in the program down (those with captures have this penalty in either case)! See How do I get what is to the left of my match? and perlre. So use with care!
$line =~ m{\d+}g; my $pos = pos($line) - length $&;
This third solution can be seen as a compromise between the first two solutions. Using $& will also affect all other regular expressions negativly, but "[...] As of 5.005, $& is not so costly as the other two" (perlre).

Since Perl 5.6.0, there exists a forth way of retrieving the match position:

$line =~ m{\d+}; my $pos = $-[0];
See perlvar @LAST_MATCH_START. This solution does not impose a performance penalty on all regular expression matches and is therefore recommended.

Comment on Answer: How do I retrieve the position of the first occurrence of a match?
Select or Download Code
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (7)
As of 2014-12-26 09:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (171 votes), past polls