|Keep It Simple, Stupid|
Avoiding regex backtrackingby Aristotle (Chancellor)
|on Mar 05, 2002 at 13:25 UTC||Need Help??|
Aristotle has asked for the
wisdom of the Perl Monks concerning the following question:
I just read the section on regexes in Camel 3 a few days ago and now I understand why Ovid posted Death to Dot Star! many moons ago. Now, I was trying to come up with a universal way to express a backtracking free vesion of a regex. Personally, I almost never use .* alone - it's .*? in 99.9% of my regexes. What I'm looking for is a way to convert a .*?xyz into a backtracking free construct where xyz may be an arbitrarily long string.
So let's say I have /(.*?)\send;/. The "simple" way I came up with is /((?!\send;).)*\send;/. But, that's still a dot metacharacter and besides, to me it doesn't seem to me to really do any less work than the .*? (it just reverses the order of work by testing for \send; first before eating the next character, where the engine would eat the character and then test). Obviously that's not what I'm after. My next idea was /(\S|(?!\send;)\s)*\send;/. Is that as much as I can hope for?
This generalizes to testing for whether we have either the negated first character out of the constant string or not the constant string in a lookahead in front of the first character out of the string. The savings is when we can eat a character due to the first case (not equal to the first character in the string) because we don't need any string comparison and can look at just the character in question. A subtle difference as noted by Ovid in his node is that a negated character class will eat newlines, which the dot would not usually do.
Assuming I haven't made any grave mistakes or flawed assumptions, then forgive my hubris but shouldn't the regex engine be capable of optimizing this case without further teeth clenching on the programmer's side since every .*?xyz generalizes to (^x|(?!xyz)x)*xyz? (In fact, I don't see why it shouldn't work for arbitrary regexes in place of just a constant xyz string.)
Can someone enlighten me?
Makeshifts last the longest.