This guide is for code that matches patterns or strings it did not
write: a pattern typed by a user, lines from a file someone uploaded. It
shows how a match can take very long, how re_limits() stops
it, and what the limits do not promise.
The problem
PCRE2 matches by backtracking: when one way of matching fails, it
goes back and tries the next. A pattern with a repeat inside a repeat,
such as ^(a+)+$, has a number of ways that doubles with
each extra a, and a subject that almost matches makes PCRE2
try them all. Twenty as and a ! still get an
answer. Thirty do not: the search runs into PCRE2’s own limit of ten
million steps, and the call fails.
subject <- function(n) paste0(strrep("a", n), "!")
re_detect(subject(20), "^(a+)+$")
#> [1] FALSE
re_detect(subject(30), "^(a+)+$")
#> Error in `re_detect()`:
#> ! Element 1 of `x` hit the match limit: match limit exceeded. See `?re_limits`.So a match cannot run for ever. But ten million steps is a lot of work to spend on each bad string in a long vector, and the error loses the answers for the good ones.
Set a limit for a call
Every matching function takes limits, made by
re_limits(). match is the number of steps one
search may take. Here it is ten thousand, a thousandth of the default.
The error has the class zuregex_error_limit, so you can
tell it from a pattern that does not compile, and handle it.
Keep the elements that finished
One bad string should not always lose the whole vector. With
on_limit = "na", an element that hits a limit is
NA, the others are matched as usual, and the call gives one
warning that counts the NAs. The second element here is
TRUE.
re_detect(x, "^(a+)+$", limits = re_limits(match = 1e4, on_limit = "na"))
#> Warning in re_detect(x, "^(a+)+$", limits = re_limits(match = 10000, on_limit =
#> "na")): 1 element of `x` hit a match limit and is `NA`.
#> [1] NA TRUEThe warning has the class zuregex_warning_limit.
Set a limit for the session
The option zuregex.limits applies to every call that
does not pass limits itself. Printing the object shows what
it holds.
What the limits do not promise
- Not linear time. A limit bounds the work for each element; it does not make the pattern cheap. For a guarantee that matching time grows only with the length of the input, use the re2 package.
-
Not a time in seconds.
matchcounts PCRE2’s steps, which differ in cost from pattern to pattern. Choose it by trying your real patterns. -
Not compiling. The limits bound matching. Compiling
is bounded separately: a compiled pattern may take at most 16 MiB, which
re_compile_size()changes. -
depthandheapbind only the interpreter. PCRE2’s just-in-time compiler honoursmatchand ignores the other two, somatchis the limit to rely on.
See also
?re_limits describes each limit and PCRE2’s defaults.
The C API has the same limits; see Link to
zuregex from C.