⭐ in reply to How can I use backrefs in a lookbehind?
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:/.. # 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
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:/(?<= # 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
/.. # 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
|
|---|