Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Re: Quick Regex trouble

by kennethk (Abbot)
on Jul 16, 2013 at 20:47 UTC ( #1044655=note: print w/replies, xml ) Need Help??

in reply to Quick Regex trouble

Close; you need a negative look-behind assertion:
#!/usr/bin/perl use strict; use warnings; my $var = "use neighbor 2001:504:0:4::6181:1"; ($var =~/(?<!use )neighbor[[:alpha:]-]* ([[:alnum:]\.-:]+)/) and do{ print $1; };

#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Replies are listed 'Best First'.
Re^2: Quick Regex trouble
by 2teez (Vicar) on Jul 16, 2013 at 21:16 UTC

    NOTEI think it's actually look-behind assertion he needs.

    ($var =~/(?<=use )neighbor[[:alpha:]-]* ([[:alnum:]\.-:]+)/) and do{ print $1; };
    output 2001:504:0:4::6181:1 If that is the output the OP wanted.

    Because with "negative look-behind assertion", the match is not successful (failed). In fact, there is no output.
    Checked with use re 'debug';
    .. produces ..

    NOTE: I think I got this wrong, and kennethk was right! Since, the OP gave a condition on which the regex should match as "when the string doesn't have USE" and the sample he gave has it.

    If you tell me, I'll forget.
    If you show me, I'll remember.
    if you involve me, I'll understand.
    --- Author unknown to me

      I think it's actually look-behind assertion he needs.

      I don't think so. The OP said that it should match "neighbor" but not "use neighbor", so that a zero-width negative look-behind assertion seems to be what is needed to exclude "use".

      Just an additional note: the do {} block is unnecessary in the OP code. The solution could be:

      ($var =~/(?<!use )neighbor[[:alpha:]-]* ([[:alnum:]\.-:]+)/) and print $1;

      or even:

      print $1 if $var =~/(?<!use )neighbor[[:alpha:]-]* ([\d:]+)/;

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1044655]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (5)
As of 2018-06-23 10:27 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (125 votes). Check out past polls.