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

Couldn't find anything in perlre about this one. I'd like to start a regexp halfway through a string. I could just cut the string at my current position, search that then calculate the offset for the original string, but we're here to make the easy jobs easy, right?

Being able to search backwards would be nice too but I'm pretty sure I'll have to reverse the string for that.

____________________
Jeremy
I didn't believe in evil until I dated it.

  • Comment on Can I start a regular expression half way through a string

Replies are listed 'Best First'.
Re (tilly) 1: Can I start a regular expression half way through a string
by tilly (Archbishop) on Nov 03, 2001 at 07:20 UTC
    Assign to pos and then do a /g match.
Re: Can I start a regular expression half way through a string
by Fastolfe (Vicar) on Nov 03, 2001 at 07:11 UTC
    You can skip $skip characters pretty efficiently simply by using /.{$skip}/. There's probably an index somewhere, since the regular expression engine needs it to keep track of /g matches, but I don't know how to directly access it. (It's pos, as tilly noted below.)

    Update: wog reminds us that this requires the /s modifier, or a re-write as /(?s:.{$skip})/ to catch newlines as well.

Re: Can I start a regular expression half way through a string
by clintp (Curate) on Nov 03, 2001 at 18:41 UTC
    substr is great for this kind of problem:
    substr($foo,5)=~/HLAG/; # Only beyond the 5th char substr($foo,10,100)=~s/narf/poit/g;
    And so on. The nice thing is you can contain the end of the match as well as where to start.

    Afterthought: This bind-operator trick can also be used with reverse for nonsense like:

    (reverse $foo)=~/dlroW/;
    But this doesn't work with s///, of course.