http://www.perlmonks.org?node_id=1044655


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 ..


    UPDATE:
    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:]+)/;