Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

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 all is quiet...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2018-01-17 09:54 GMT
Find Nodes?
    Voting Booth?
    How did you see in the new year?

    Results (198 votes). Check out past polls.