Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Look Ahead:

by nvivek (Vicar)
on Apr 02, 2010 at 08:21 UTC ( [id://832445]=perlquestion: print w/replies, xml ) Need Help??

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

why look ahead ?= isn't working if we give pattern after it. For ex,
if($str=~/([0-9]+)(?=welcome)to india/) { print "Matched\n"; }
My input string is as follows: 1welcometo india. Why it isn't getting matched? But,it gets matched when I used .* instead of "to india" after (?=welcome) in the pattern.

Replies are listed 'Best First'.
Re: Look Ahead:
by BrowserUk (Patriarch) on Apr 02, 2010 at 09:38 UTC

    Because lookaheads are "zero length" matches. That is they do not consume any of the string that they match. So, in your example,

    1welcometo india. ^...............is matched and consumed by ([0-9]+) ^^^^^^^........is matched but not consumed by (?=welcome) ^..............so "to india" tries to match here and fails.

    This does match though:

    $str = '1welcometo india';; $str =~ m/([0-9]+)(?=welcome)welcometo india/ and print 'matched';; matched

    It's called 'lookahead' because it looks ahead but doesn't travel there.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      Yeah,Thank you very much.I learnt about it and I also learnt about look behind operator in the regular expression.
Re: Look Ahead:
by rmflow (Beadle) on Apr 02, 2010 at 08:39 UTC
    because it must be /([0-9]+)(?=welcome)welcometo india/ to match
      I knew how to match the string but I want to know why it is working like that?Explain me?
        Because sometimes you need to look ahead without actual matching.

        For example:
        $num = scalar reverse "1000000000000"; $num =~ s/(\d\d\d(?=\d))/\1,/g; print scalar reverse $num;
        will print 1,000,000,000,000
Re: Look Ahead:
by Anonymous Monk on Apr 02, 2010 at 08:52 UTC
    If you
    use re 'debug';
    you get to see how the regex engine does matching

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://832445]
Approved by mr_mischief
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (2)
As of 2024-04-19 01:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found