Menu

1 / 5

regex-engine: a regex engine from scratch in Rust, with no backtracking

DEV Community: rust·Abdeldjalil Chougui·18 days ago
#sMRIOiYb
#devtorust#devto#dev#regex#engine
Long article (1304 words) — no AI summary yet.
Reading 0:00
15s threshold

Regular expressions are one of those tools we use without asking how they work. Then one day a pattern like (a+)+$ meets a long input, and a service hangs. That failure has a name, catastrophic backtracking, and it is not a law of nature. It comes from one way of implementing regexes. There is another way, older and based on automata, that runs in time linear in the input no matter what the pattern is.

Russ Cox described that approach in a well-known series of articles. regex-engine is my implementation of it in Rust, written from scratch: a parser, a Thompson NFA, a Pike VM and a lazy DFA. It does not backtrack, and its results are checked against the regex crate by differential testing. This post is about what I built and what it teaches.

What I built

The engine is a pipeline of four stages.

1. The parser ( parser.rs ) is a recursive descent parser that produces an AST. Every literal, class and escape becomes a sorted list of char ranges, so the later stages only ever see one kind of leaf.

2.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.