Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

Re: Regex question is this one of those look (ahead|behind)s ?

by kennethk (Abbot)
on Mar 25, 2014 at 18:20 UTC ( #1079716=note: print w/replies, xml ) Need Help??

in reply to Regex question is this one of those look (ahead|behind)s ?

use strict; use warnings; use YAPE::Regex::Explain; print YAPE::Regex::Explain->new(qr/^(?<!abc)def/)->explain;
tells us
The regular expression: (?-imsx:^(?<!abc)def) matches as follows: NODE EXPLANATION ---------------------------------------------------------------------- (?-imsx: group, but do not capture (case-sensitive) (with ^ and $ matching normally) (with . not matching \n) (matching whitespace and # normally): ---------------------------------------------------------------------- ^ the beginning of the string ---------------------------------------------------------------------- (?<! look behind to see if there is not: ---------------------------------------------------------------------- abc 'abc' ---------------------------------------------------------------------- ) end of look-behind ---------------------------------------------------------------------- def 'def' ---------------------------------------------------------------------- ) end of grouping ----------------------------------------------------------------------

Look aheads and look behinds are zero-width. This means that your regular expression is a subset of /^def/, which is clearly not what you intend. There are a number of ways to get what you express above. Probably the most natural would be s/(?<!^abc)\Kdef/xyz/. Moving the ^ inside the negative look behind means it only matters if the a starts the string. \K means 'keep everything before this' (see Character Classes and other Special Escapes)

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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1079716]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (7)
As of 2016-10-28 06:31 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (375 votes). Check out past polls.