Reading — step 1 of 5
Read
Quantifiers: ? * +
Quantifiers turn an atom into "match this between N and M times":
| Quantifier | Meaning |
|---|---|
? | 0 or 1 (optional) |
* | 0 or more |
+ | 1 or more |
{n} | exactly n |
{n,} | at least n |
{n,m} | between n and m (inclusive) |
By default they are greedy: match as many as possible, then backtrack.
Append ? to make non-greedy: .*?.
The simplest implementation: backtracking recursive match.
This works but catastrophic backtracking is real: (a+)+b on
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa! takes exponential time in
backtracking engines. NFA simulation (next chapter) avoids this completely.
The NFA approach: at each text position, the engine maintains a set of possible NFA states. Each step transitions all states in parallel. Since the state count is bounded by the regex length, runtime is O(n*m) — never exponential.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…