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 :-)


In reply to Re: Using index when the substring as is a regular expression by Corion
in thread Using index when the substring as is a regular expression by rbi

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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, details, 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, summary, 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.