From: Robert Citek <[EMAIL PROTECTED]>
> Is there an equivalent for "index" that uses regular expressions
> instead of exact string?
> 
> I've been looking at index, pos, m//, and the corresponding "$" 
> variables but nothing I've found so far does what I'm looking for. 
> Specifically, what I'm trying to do is find all the starting locations
> of a RE match.  For example, using an exact string match:
> 
> $ perl -e '$foo="baaaab"; $re="aa" ;
>             for ($bar=index($foo, $re); $bar >= 0 ; $bar=index($foo,
> $re, $bar+1))
>               { print $bar, "\t" }
>             print "\n" ; '
> 1       2       3
> 
> I'd like to do the same except use a regular expression.  BTW, notice
> that matches can overlap.
> 
> Any thoughts or ideas?

How about this:

        $s = "sasas dfgfgh asasas asedsase";

        while ($s =~ /\G.*?(?=sas)./g) {
                print "pos=",pos($s)-1, " = '",substr($s,pos($s)-1,3),"'\n";
        }

the "sas" is the regexp being matched.

The \G matches where the last match left off, the .*? skips as few 
characters as possible, the (?=) makes sure the regexp matches at 
that place, but doesn't move the position in string and the . at the 
end moves the position so that the next round doesn't find the same 
occurrence. That's also why I have to subtrct the 1 from the pos($s).

You could also do this:

        while ($s =~ /\G.+?(?=sas)/g) {
                print "pos=",pos($s), " = '",substr($s,pos($s),3),"'\n";
        }

Which looks a bit nicer, but it would miss the match at the very 
beginning of the string.

HTH, Jenda
===== [EMAIL PROTECTED] === http://Jenda.Krynicky.cz =====
When it comes to wine, women and song, wizards are allowed 
to get drunk and croon as much as they like.
        -- Terry Pratchett in Sourcery


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to