You are correct that the pattern .*?foo can be written as (?:[^f]+|f(?!oo))*foo, or the variant you showed. You are correct in assuming that this general principle can be used for practically any regex.

However, you should "unroll the loop" of that regex. Look at these results:

use Benchmark 'cmpthese'; my $str = "this is the best end"; cmpthese(-5, { extra => sub { $str =~ /(?:[^e]+|e(?!nd))*end/ }, plain => sub { $str =~ /.*?end/ }, }); __END__ extra: 12019.37/s (n=60818) plain: 49615.59/s (n=283305) Rate extra plain extra 12019/s -- -76% plain 49616/s 313% --
If we unroll the loop, we get better results.
use Benchmark 'cmpthese'; my $str = "this is the best end"; cmpthese(-5, { extra => sub { $str =~ /(?:[^e]+|e(?!nd))*end/ }, plain => sub { $str =~ /.*?end/ }, uroll => sub { $str =~ /[^e]*(?:e(?!nd)[^e]*)*end/ }, }); __END__ extra: 11711.62/s (n=61486) plain: 49329.33/s (n=250593) uroll: 17985.61/s (n=94964) Rate extra uroll plain extra 11712/s -- -35% -76% uroll 17986/s 54% -- -64% plain 49329/s 321% 174% --
But the point is, the internal optimization uses less regex op-codes, and so it is faster -- it has the engine do the work itself, it doesn't make the regex do the work.

_____________________________________________________
Jeff[japhy]Pinyan: Perl, regex, and perl hacker, who'd like a (from-home) job
s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;


In reply to Re: Avoiding regex backtracking by japhy
in thread Avoiding regex backtracking by Aristotle

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.