Reading — step 1 of 5
Read
~1 min readBasic Matching
Literal Substring Matching
A regex engine starts as a glorified strstr(). The simplest "regex" is a
literal pattern that matches the same characters in the input:
pattern: "cat"
text: "the cat sat"
^^^ <- match at index 4
The naive O(n*m) algorithm:
for i in 0..len(text)-len(pattern):
if text[i:i+len(pattern)] == pattern:
return i
return -1
This is what we build on. Real regex engines layer:
- Literal matching (this lesson)
- Single-char wildcards (
.) - Character classes (
[a-z],\d,\w) - Quantifiers (
?,*,+,{n,m}) - Anchors (
^,$,\b) - Groups, alternation, backreferences
Each layer requires either backtracking (PCRE, JavaScript, Python re) or
NFA simulation (RE2, Go, Rust regex crate). Backtracking is simpler; NFA
guarantees linear time.
For now: just find the first occurrence of a literal pattern.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…