Skip to content
Literal Substring Matching
step 1/5

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:

  1. Literal matching (this lesson)
  2. Single-char wildcards (.)
  3. Character classes ([a-z], \d, \w)
  4. Quantifiers (?, *, +, {n,m})
  5. Anchors (^, $, \b)
  6. 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…