OnionKnight has asked for the wisdom of the Perl Monks concerning the following question:

Can you have a RegExp return the index where it found the match in a string? Just like the index() function, except with a regex. I know Javascript can.

2005-09-10 Retitled by holli, as per Monastery guidelines
Original title: 'RegExps'

  • Comment on Finding the index of a string with a regexp

Replies are listed 'Best First'.
Re: Finding the index of a string with a regexp
by sk (Curate) on Sep 09, 2005 at 23:21 UTC
     perldoc -f pos

    pos SCALAR pos Returns the offset of where the last "m//g" search left off for the variable in question ($_ is used when the variable is not specified). May be modified to change that offset. Such modification will also influence the "\G" zero-width assertion in regular expressions. See perlre and perlop.

    here is an example -

    #!/usr/bin/perl -w my $state = "mississippi"; while ($state =~ /.i/g) { print pos($state),":",$&,$/; } __END__ 2:mi 5:si 8:si 11:pi

    hope this helps!

    cheers

    SK

      That's what I'm looking for, but isn't there any way to get it to return the offset for the beginning of the match instead of the end?
        Look at the arrays @- and @+, which point to the start resp. the end of submatches — use index 0 for the whole match. So you want $-[0].

        Plus: unlike pos, it works without using /g, too.

        You didn't really think Javascript could do something with regexps that Perl couldn't, did you? Where did you think its implementors got the ideas from, anyway?

        The first thing that comes to mind is substracting the length of the match, like in:

        pos ($state) - length $&

        --
        David Serrano