Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Answer: How can I use backrefs in a lookbehind?

by Roy Johnson (Monsignor)
on Dec 02, 2004 at 16:00 UTC ( #411821=categorized answer: print w/replies, xml ) Need Help??

Q&A > regular expressions > How can I use backrefs in a lookbehind? - Answer contributed by Roy Johnson

Use lookbehind to count back as many chars as you want, and at the front of it, put a lookahead to check your pattern:
/.. # match first two chars (?:(.) # capture next char, then (?<= # looking behind, (?!\1\1\1) # don't allow a run of three ...) # starting three chars back ){1,4}/x
This technique can also overcome some other variable-length lookbehind situations. For example, if you want to match "bar" that is preceded by "foo" somewhere in the preceding six characters:
/(?<= # looking behind, (?=.{0,3}foo) # look for a foo preceded by up to three chars .{6}) # starting six chars back bar/x # then match bar
The thing to remember is that the lookahead can see farther than the end of the lookbehind, so you need to explicitly limit it. You could use that feature to get a slightly different solution to the first problem:
/.. # match first two chars (?: (?<= # looking behind, (?!(.)\1\1) # don't allow a run of three ..) # starting only two chars back . # then match the next char ){1,4}/x

Log In?

What's my password?
Create A New User
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (9)
As of 2017-09-21 11:12 GMT
Find Nodes?
    Voting Booth?
    During the recent solar eclipse, I:

    Results (245 votes). Check out past polls.