http://qs321.pair.com?node_id=24661


in reply to Death to Dot Star!

Aha! One of the classic mistakes was made on this code:
$myvar =~ /" # First quote ( # Capture text to $1 (?: # Non-backreferencing parentheses [^?"] # Anything that's not a question mark or quote | # or \?[^"] # A question mark not followed by a quote (to a +llow embedded question marks) )* # Zero or more ) # End capture \?"/x; # Followed by a question mark and quote
Try this with
$myvar = q{ abc"def??"ghi?"jkl };
And you'll see that it matches the ghi, not def??. The problem is that the "question mark NOT followed by a quote" can sometimes eat up the question mark that you need to begin your closing delimiter.

The proper way to tackle this is to "inch-along"...

$myvar = q{ abc"def??"ghi?"jkl }; print "matched <$1>" if $myvar =~ /" # First quote ( # Capture text to $1 (?: # Non-backreferencing parentheses (?!\?") # not question quote? . # ok to inch along )* # Zero or more ) # End capture \?"/sx; # Followed by a question mark and quote
which properly prints:
matched <def?>

I was tackling this kind of thing a lot when people would keep posing the "how do I match a C comment?" back in the early days Pre-Ilya-RE. I got pretty good at breaking just about any regex that claimed to match a comment, by undoing any assumption made.

-- Randal L. Schwartz, Perl hacker