Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

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

by lima1 (Curate)
on Oct 04, 2007 at 15:59 UTC ( #642690=categorized question: print w/replies, xml ) Need Help??
Contributed by lima1 on Oct 04, 2007 at 15:59 UTC
Q&A  > regular expressions


I need the position of a regular expression match. For example:
$a = "foo 123 bar"; if ($a =~ m{\d+}xms) { # code that returns 4, the position of 123 }

Answer: 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.

Please (register and) log in if you wish to add an answer

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?

    What's my password?
    Create A New User
    and all is quiet...

    How do I use this? | Other CB clients
    Other Users?
    Others musing on the Monastery: (4)
    As of 2018-07-19 02:29 GMT
    Find Nodes?
      Voting Booth?
      It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

      Results (398 votes). Check out past polls.