I've benchmarked four regexes. First the one that you claimed to be your original (which actually isn't quite correct, as it doesn't deal with backslashes correctly). Then Hugo's suggestion. Third, the standard unrolling technique - but one that has different cases for double and single quotes, and finally, one that uses unrolling, and doesn't have different cases for single and double quotes.
#!/usr/bin/perl use strict; use warnings; use Benchmark qw /cmpthese/; our $orig = qr {( [^"']+ | (?:"(?:[^"]|\\")*") | (?:'(?:[^']|\\')*') )}xs; our $hv = qr {( [^"']+ | (["']) (?: \\ . | (?!\2) . )* \2 )}xs; our $unroll = qr {( [^"']+ | " [^"]* (?: \\. [^"]*)* " | ' [^']* (?: \\. [^']*)* ' )}xs; our $code = qr {( [^"']+ | (["']) (??{ "[^$2]*(?:\\\\.[^$2]*)*" }) \2 )}xs; our $str = `cat /tmp/pp.c`; # pp.c from the perl 5.8.5 sources. cmpthese(-10, { orig => 'while ($str =~ /$orig/g) {1}', hv => 'while ($str =~ /$hv/g) {1}', unroll => 'while ($str =~ /$unroll/g) {1}', code => 'while ($str =~ /$code/g) {1}', }); __END__ Rate orig hv code unroll orig 13.0/s -- -3% -92% -96% hv 13.4/s 3% -- -92% -96% code 166/s 1179% 1139% -- -52% unroll 344/s 2546% 2464% 107% --
Note the huge benefits of unrolling.

In reply to Re: Regex weirdness? (Benchmark) by Anonymous Monk
in thread Regex weirdness? by Pic

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.