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

Hello,

Sorry if this question has been asked before.

The index function returns the position of the first occurrence of a substring in a string. Is there a regular expression version of the index function or is there a way to write a subroutine that would do this?

Thank you in advance for your help.

Richard

  • Comment on Is there a regular expression version of the index function?

Replies are listed 'Best First'.
Re: Is there a regular expression version of the index function?
by rob_au (Abbot) on Jun 20, 2004 at 12:16 UTC

    You can do this using the pos function when performing matching against a string - This function 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).

    The following code demonstrates this function in action:

    #!/opt/bin/perl $str = 'The quick brown fox jumps over the lazy dog.'; while ( $str =~ /[aeiou]/ig ) { printf( "%d %s\n", pos( $str ), substr( $str, pos( $str ) - 1 ) ); substr( $str, 0, pos( $str ), '' ); }

     

    perl -le "print unpack'N', pack'B32', '00000000000000000000001011100101'"

Re: Is there a regular expression version of the index function?
by Sidhekin (Priest) on Jun 20, 2004 at 12:25 UTC

    If you are already using regexes, @- is all you need. But if you are just looking for a drop-in replacement for index, well, I have used this:

    sub regindex { my ($str, $rx, $pos) = @_; pos($str) = $pos || 0; $str =~ /$rx/g or return -1; return $-[0]; }

    print "Just another Perl ${\(trickster and hacker)},"
    The Sidhekin proves Sidhe did it!

      Thank you all for your help. I am now reading about the pos function.

      Richard

        Oops. As you demonstrated in your example, $-[0] is what I'm looking for. According to perldoc:

        "...$-[0] is the offset into the string of the beginning of the entire match..."

        Thanks again.

        Richard

Re: Is there a regular expression version of the index function?
by Fletch (Bishop) on Jun 20, 2004 at 12:12 UTC

    See perldoc perlvar for @- and @+.

Re: Is there a regular expression version of the index function?
by muba (Priest) on Jun 20, 2004 at 17:17 UTC
    - Why would you want to know this?
    - What's wrong with the index() function?
      index() doesn't work with regexen.

      We're not really tightening our belts, it just feels that way because we're getting fatter.