Patch #731514: Update recursion documentation to mention simple recursion.

This commit is contained in:
Martin v. Löwis 2003-05-03 10:57:53 +00:00
parent cd12bfc142
commit 7829e5661c
1 changed files with 14 additions and 11 deletions

View File

@ -896,15 +896,16 @@ The equivalent regular expression would be
(\S+) - (\d+) errors, (\d+) warnings (\S+) - (\d+) errors, (\d+) warnings
\end{verbatim} \end{verbatim}
\leftline{\strong{Avoiding backtracking}} \leftline{\strong{Avoiding recursion}}
If you create regular expressions that require the engine to perform a lot If you create regular expressions that require the engine to perform a
of backtracking, you may encounter a RuntimeError exception with the message lot of recursion, you may encounter a RuntimeError exception with
\code{maximum recursion limit exceeded}. For example, the message \code{maximum recursion limit} exceeded. For example,
\begin{verbatim} \begin{verbatim}
>>> s = "<" + "that's a very big string!"*1000 + ">" >>> import re
>>> re.match('<.*?>', s) >>> s = 'Begin ' + 1000*'a very long string ' + 'end'
>>> re.match('Begin (\w| )*? end', s).end()
Traceback (most recent call last): Traceback (most recent call last):
File "<stdin>", line 1, in ? File "<stdin>", line 1, in ?
File "/usr/local/lib/python2.3/sre.py", line 132, in match File "/usr/local/lib/python2.3/sre.py", line 132, in match
@ -912,8 +913,10 @@ Traceback (most recent call last):
RuntimeError: maximum recursion limit exceeded RuntimeError: maximum recursion limit exceeded
\end{verbatim} \end{verbatim}
You can often restructure your regular expression to avoid backtracking. You can often restructure your regular expression to avoid recursion.
The above regular expression can be recast as
\regexp{\textless[\textasciicircum \textgreater]*\textgreater}. As a \versionadded[Simple uses of the \regexp{*?} pattern are now
further benefit, such regular expressions will run faster than their special-cased to avoid recursion. Thus, the above regular expression
backtracking equivalents. can avoid recursion by being recast as \regexp{Begin [a-zA-Z0-9_ ]*?end}.
As a further benefit, such regular expressions will run faster than
their recursive equivalents.]{2.3}