nom > regex

106 points quarterque

Hi folks, I’m from an industry background (C#, Typescript, Bash, etc.). I recently had to validate a string in Rust, and I found myself automatically reaching for regex. This time I thought better of it and tried out nom on recommendation, and I’ve got to say it’s way better!

I was initially confused by how generic nom is, but once I started specifying ::<&str> in function calls it was a breeze.

So why is it better than regex?

  1. nom is smaller because it does not need to embed a regex compiler in your program.
  2. You can add context to each match (e.g. context("Expect version separator", char('.')), so you’ll get specific details for the segment you matched, or failed to match.
  3. Each nom “combinator” returns what it matched. It’s often difficult to tell what part of a regex expression matched what part of the input. That’s almost never the case with nom.
  4. If you want more robust failure options, nom errors can be customized and extended with the nom_supreme crate, which can dump the full state of the parsing tree.