Back when I wrote

perlretut , code expressions (?{code}) and (??{code}) were
relatively new beasts in the regex menagerie. I thought they were clever
and the variable backtracking was a little bit magical.

The trouble was, I couldn't come up with any examples where code
expressions really nailed the problem. So for the tutorial I created a
cute, but useless, example of matching Fibonacci strings:

`# detects if a binary string 1101010010001...
# has a Fibonacci spacing 0,1,1,2,3,5,... of the 1's
$x = "1101010010001000001";
$s0 = 0; $s1 = 1; # initial conditions
print "It is a Fibonacci sequence\n"
if $x =~ /^1 # match an initial '1'
(
(??{'0' x $s0}) # match $s0 of '0'
1 # and then a '1'
(?{
$largest = $s0; # largest seq so far
$s2 = $s1 + $s0; # compute next term
$s0 = $s1; # in Fibonacci sequence
$s1 = $s2;
})
)+ # repeat as needed
$ # that is all there is
/x;
print "Largest sequence matched was $largest\n";
`

This prints

` It is a Fibonacci sequence
Largest sequence matched was 5
`

Since then, I have written many regexes, but haven't come across any
code that

* needed * code expressions, as opposed to a combination of
simpler regexes and perl code.

My question is: Has anyone found a good use for code expressions in
their regex work?

-Mark

Comment onUseful Uses of regex code expressions?SelectorDownloadCode