This is the manual of nom from docs.rs.

1 nom, eating data byte by byte

nom is a parser combinator library with a focus on safe parsing, streaming patterns, and as much as possible zero copy.

Example

extern crate nom;

use nom::{
  IResult,
  bytes::complete::{tag, take_while_m_n},
  combinator::map_res,
  sequence::tuple
};

#[derive(Debug,PartialEq)]
pub struct Color {
  pub red:     u8,
  pub green:   u8,
  pub blue:    u8,
}

fn from_hex(input: &str) -> Result<u8, std::num::ParseIntError> {
  u8::from_str_radix(input, 16)
}

fn is_hex_digit(c: char) -> bool {
  c.is_digit(16)
}

fn hex_primary(input: &str) -> IResult<&str, u8> {
  map_res(
    take_while_m_n(2, 2, is_hex_digit),
    from_hex
  )(input)
}

fn hex_color(input: &str) -> IResult<&str, Color> {
  let (input, _) = tag("#")(input)?;
  let (input, (red, green, blue)) = tuple((hex_primary, hex_primary, hex_primary))(input)?;

  Ok((input, Color { red, green, blue }))
}

fn main() {
  assert_eq!(hex_color("#2F14DF"), Ok(("", Color {
    red: 47,
    green: 20,
    blue: 223,
  })));
}

The code is available on Github

There are a few guides with more details about the design of nom macros, how to write parsers, or the error management system. You can also check out the [recipes] module that contains examples of common patterns.

Looking for a specific combinator? Read the "choose a combinator" guide

If you are upgrading to nom 5.0, please read the migration document.

See also the FAQ.

2 Parser combinators

Parser combinators are an approach to parsers that is very different from software like lex and yacc. Instead of writing the grammar in a separate syntax and generating the corresponding code, you use very small functions with very specific purposes, like "take 5 bytes", or "recognize the word 'HTTP'", and assemble them in meaningful patterns like "recognize 'HTTP', then a space, then a version". The resulting code is small, and looks like the grammar you would have written with other parser approaches.

This gives us a few advantages:

  • The parsers are small and easy to write
  • The parsers components are easy to reuse (if they're general enough, please add them to nom!)
  • The parsers components are easy to test separately (unit tests and property-based tests)
  • The parser combination code looks close to the grammar you would have written
  • You can build partial parsers, specific to the data you need at the moment, and ignore the rest

Here is an example of one such parser, to recognize text between parentheses:

use nom::{
  IResult,
  sequence::delimited,
  // see the "streaming/complete" paragraph lower for an explanation of these submodules
  character::complete::char,
  bytes::complete::is_not
};

fn parens(input: &str) -> IResult<&str, &str> {
  delimited(char('('), is_not(")"), char(')'))(input)
}

It defines a function named parens which will recognize a sequence of the character (, the longest byte array not containing ), then the character ), and will return the byte array in the middle.

Here is another parser, written without using nom's combinators this time:

#[macro_use]
extern crate nom;

use nom::{IResult, Err, Needed};

fn main() {
  fn take4(i: &[u8]) -> IResult<&[u8], &[u8]>{
    if i.len() < 4 {
      Err(Err::Incomplete(Needed::new(4)))
    } else {
      Ok((&i[4..], &i[0..4]))
    }
  }
}

This function takes a byte array as input, and tries to consume 4 bytes. Writing all the parsers manually, like this, is dangerous, despite Rust's safety features. There are still a lot of mistakes one can make. That's why nom provides a list of function and macros to help in developing parsers.

With functions, you would write it like this:

use nom::{IResult, bytes::streaming::take};
fn take4(input: &str) -> IResult<&str, &str> {
  take(4u8)(input)
}

With macros, you would write it like this:

#[macro_use]
extern crate nom;

fn main() {
  named!(take4, take!(4));
}

nom has used macros for combinators from versions 1 to 4, and from version 5, it proposes new combinators as functions, but still allows the macros style (macros have been rewritten to use the functions under the hood). For new parsers, we recommend using the functions instead of macros, since rustc messages will be much easier to understand.

A parser in nom is a function which, for an input type I, an output type O and an optional error type E, will have the following signature:

fn parser(input: I) -> IResult<I, O, E>;

Or like this, if you don't want to specify a custom error type (it will be (I, ErrorKind) by default):

fn parser(input: I) -> IResult<I, O>;

IResult is an alias for the Result type:

use nom::{Needed, error::ErrorKind};

type IResult<I, O, E = (I,ErrorKind)> = Result<(I, O), Err<E>>;

enum Err<E> {
  Incomplete(Needed),
  Error(E),
  Failure(E),
}

It can have the following values:

  • A correct result Ok((I,O)) with the first element being the remaining of the input (not parsed yet), and the second the output value;
  • An error Err(Err::Error(c)) with c an error that can be built from the input position and a parser specific error
  • An error Err(Err::Incomplete(Needed)) indicating that more input is necessary. Needed can indicate how much data is needed
  • An error Err(Err::Failure(c)). It works like the Error case, except it indicates an unrecoverable error: We cannot backtrack and test another parser

Please refer to the "choose a combinator" guide for an exhaustive list of parsers. See also the rest of the documentation here.

3 Making new parsers with function combinators

nom is based on functions that generate parsers, with a signature like this: (arguments) -> impl Fn(Input) -> IResult<Input, Output, Error>. The arguments of a combinator can be direct values (like take which uses a number of bytes or character as argument) or even other parsers (like delimited which takes as argument 3 parsers, and returns the result of the second one if all are successful).

Here are some examples:

use nom::IResult;
use nom::bytes::complete::{tag, take};
fn abcd_parser(i: &str) -> IResult<&str, &str> {
  tag("abcd")(i) // will consume bytes if the input begins with "abcd"
}

fn take_10(i: &[u8]) -> IResult<&[u8], &[u8]> {
  take(10u8)(i) // will consume and return 10 bytes of input
}

4 Combining parsers

There are higher level patterns, like the alt combinator, which provides a choice between multiple parsers. If one branch fails, it tries the next, and returns the result of the first parser that succeeds:

use nom::IResult;
use nom::branch::alt;
use nom::bytes::complete::tag;

let mut alt_tags = alt((tag("abcd"), tag("efgh")));

assert_eq!(alt_tags(&b"abcdxxx"[..]), Ok((&b"xxx"[..], &b"abcd"[..])));
assert_eq!(alt_tags(&b"efghxxx"[..]), Ok((&b"xxx"[..], &b"efgh"[..])));
assert_eq!(alt_tags(&b"ijklxxx"[..]), Err(nom::Err::Error((&b"ijklxxx"[..], nom::error::ErrorKind::Tag))));

The opt combinator makes a parser optional. If the child parser returns an error, opt will still succeed and return None:

use nom::{IResult, combinator::opt, bytes::complete::tag};
fn abcd_opt(i: &[u8]) -> IResult<&[u8], Option<&[u8]>> {
  opt(tag("abcd"))(i)
}

assert_eq!(abcd_opt(&b"abcdxxx"[..]), Ok((&b"xxx"[..], Some(&b"abcd"[..]))));
assert_eq!(abcd_opt(&b"efghxxx"[..]), Ok((&b"efghxxx"[..], None)));

many0 applies a parser 0 or more times, and returns a vector of the aggregated results:

#[macro_use] extern crate nom;
#[cfg(feature = "alloc")]
fn main() {
  use nom::{IResult, multi::many0, bytes::complete::tag};
  use std::str;

  fn multi(i: &str) -> IResult<&str, Vec<&str>> {
    many0(tag("abcd"))(i)
  }

  let a = "abcdef";
  let b = "abcdabcdef";
  let c = "azerty";
  assert_eq!(multi(a), Ok(("ef",     vec!["abcd"])));
  assert_eq!(multi(b), Ok(("ef",     vec!["abcd", "abcd"])));
  assert_eq!(multi(c), Ok(("azerty", Vec::new())));
}

[cfg(not(feature = "alloc"))]
fn main() {}

Here are some basic combining macros available:

  • opt: Will make the parser optional (if it returns the O type, the new parser returns Option<O>)
  • many0: Will apply the parser 0 or more times (if it returns the O type, the new parser returns Vec<O>)
  • many1: Will apply the parser 1 or more times

There are more complex (and more useful) parsers like tuple!, which is used to apply a series of parsers then assemble their results.

Example with tuple:

#[macro_use] extern crate nom;
fn main() {
  use nom::{error::ErrorKind, Needed,
  number::streaming::be_u16,
  bytes::streaming::{tag, take},
  sequence::tuple};

  let mut tpl = tuple((be_u16, take(3u8), tag("fg")));

  assert_eq!(
   tpl(&b"abcdefgh"[..]),
   Ok((
     &b"h"[..],
     (0x6162u16, &b"cde"[..], &b"fg"[..])
   ))
  );
  assert_eq!(tpl(&b"abcde"[..]), Err(nom::Err::Incomplete(Needed::new(2))));
  let input = &b"abcdejk"[..];
  assert_eq!(tpl(input), Err(nom::Err::Error((&input[5..], ErrorKind::Tag))));
}

But you can also use a sequence of combinators written in imperative style, thanks to the ? operator:

#[macro_use] extern crate nom;
fn main() {
  use nom::{IResult, bytes::complete::tag};

  #[derive(Debug, PartialEq)]
  struct A {
    a: u8,
    b: u8
  }

  fn ret_int1(i:&[u8]) -> IResult<&[u8], u8> { Ok((i,1)) }
  fn ret_int2(i:&[u8]) -> IResult<&[u8], u8> { Ok((i,2)) }

  fn f(i: &[u8]) -> IResult<&[u8], A> {
    // if successful, the parser returns `Ok((remaining_input, output_value))` that we can destructure
    let (i, _) = tag("abcd")(i)?;
    let (i, a) = ret_int1(i)?;
    let (i, _) = tag("efgh")(i)?;
    let (i, b) = ret_int2(i)?;

    Ok((i, A { a, b }))
  }

  let r = f(b"abcdefghX");
  assert_eq!(r, Ok((&b"X"[..], A{a: 1, b: 2})));
}

5 Streaming / Complete

Some of nom's modules have streaming or complete submodules. They hold different variants of the same combinators.

A streaming parser assumes that we might not have all of the input data. This can happen with some network protocol or large file parsers, where the input buffer can be full and need to be resized or refilled.

A complete parser assumes that we already have all of the input data. This will be the common case with small files that can be read entirely to memory.

Here is how it works in practice:

 use nom::{
   IResult, 
   Err, 
   Needed, 
   error::{
     Error, 
     ErrorKind
   }, 
   bytes, 
   character
 };

 fn take_streaming(i: &[u8]) -> IResult<&[u8], &[u8]> {
   bytes::streaming::take(4u8)(i)
 }

 fn take_complete(i: &[u8]) -> IResult<&[u8], &[u8]> {
   bytes::complete::take(4u8)(i)
 }

 // both parsers will take 4 bytes as expected
 assert_eq!(take_streaming(&b"abcde"[..]), Ok((&b"e"[..], &b"abcd"[..])));
 assert_eq!(take_complete(&b"abcde"[..]), Ok((&b"e"[..], &b"abcd"[..])));

 // if the input is smaller than 4 bytes, the streaming parser
 // will return `Incomplete` to indicate that we need more data
 assert_eq!(take_streaming(&b"abc"[..]), Err(Err::Incomplete(Needed::new(1))));

 // but the complete parser will return an error
 assert_eq!(take_complete(&b"abc"[..]), Err(Err::Error(Error::new(&b"abc"[..], ErrorKind::Eof))));

 // the alpha0 function recognizes 0 or more alphabetic characters
 fn alpha0_streaming(i: &str) -> IResult<&str, &str> {
   character::streaming::alpha0(i)
 }

 fn alpha0_complete(i: &str) -> IResult<&str, &str> {
   character::complete::alpha0(i)
 }

 // if there's a clear limit to the recognized characters, both 
 // parsers work the same way
 assert_eq!(alpha0_streaming("abcd;"), Ok((";", "abcd")));
 assert_eq!(alpha0_complete("abcd;"), Ok((";", "abcd")));

 // but when there's no limit, the streaming version returns 
 // `Incomplete`, because it cannot know if more input data 
 // should be recognized. The whole input could be "abcd;", 
 // or "abcde;"
 assert_eq!(alpha0_streaming("abcd"), Err(Err::Incomplete(Needed::new(1))));

 // while the complete version knows that all of the data is there
 assert_eq!(alpha0_complete("abcd"), Ok(("", "abcd")));

Going further: Read the guides, check out the recipes!

6 List of macros parsers and combinators

Note: this list is meant to provide a nicer way to find a nom macros than reading through the documentation on docs.rs, since rustdoc puts all the macros at the top level. Function combinators are organized in module so they are a bit easier to find.

6.1 Basic elements

Those are used to recognize the lowest level elements of your grammar, like, "here is a dot", or "here is an big endian integer".

combinatorusageinputoutputcomment
charchar!('a')"abc"Ok(("bc", 'a'))Matches one character (works with non ASCII chars too)
is_a is_a!("ab")"ababc"Ok(("c", "abab"))Matches a sequence of any of the characters passed as arguments
is_notis_not!("cd")"ababc"Ok(("c", "abab"))Matches a sequence of none of the characters passed as arguments
one_ofone_of!("abc")"abc"Ok(("bc", 'a'))Matches one of the provided characters (works with non ASCII characters too)
none_ofnone_of!("abc")"xyab"Ok(("yab", 'x'))Matches anything but the provided characters
tagtag!("hello")"hello world"Ok((" world", "hello"))Recognizes a specific suite of characters or bytes
tag_no_casetag_no_case!("hello")"HeLLo World"Ok((" World", "HeLLo"))Case insensitive comparison. Note that case insensitive comparison is not well defined for unicode, and that you might have bad surprises
taketake!(4)"hello"Ok(("o", "hell"))Takes a specific number of bytes or characters
take_whiletake_while!(is_alphabetic)"abc123"Ok(("123", "abc"))Returns the longest list of bytes for which the provided function returns true. take_while1 does the same, but must return at least one character
take_tilltake_till!(is_alphabetic)"123abc"Ok(("abc", "123"))Returns the longest list of bytes or characters until the provided function returns true. take_till1 does the same, but must return at least one character. This is the reverse behaviour from take_while: take_till!(f) is equivalent to take_while!(\|c\| !f(c))
take_untiltake_until!("world")"Hello world"Ok(("world", "Hello "))Returns the longest list of bytes or characters until the provided tag is found. take_until1 does the same, but must return at least one character

6.2 Choice combinators

combinatorusageinputoutputcomment
altalt!(tag!("ab") \| tag!("cd"))"cdef"Ok(("ef", "cd"))Try a list of parsers and return the result of the first successful one
switchswitch!(take!(2), "ab" => tag!("XYZ") \| "cd" => tag!("123"))"cd1234"Ok(("4", "123"))Choose the next parser depending on the result of the first one, if successful, and returns the result of the second parser
permutationpermutation!(tag!("ab"), tag!("cd"), tag!("12"))"cd12abc"Ok(("c", ("ab", "cd", "12"))Succeeds when all its child parser have succeeded, whatever the order

6.3 Sequence combinators

combinatorusageinputoutputcomment
delimiteddelimited!(char!('('), take!(2), char!(')'))"(ab)cd"Ok(("cd", "ab"))
precededpreceded!(tag!("ab"), tag!("XY"))"abXYZ"Ok(("Z", "XY"))
terminatedterminated!(tag!("ab"), tag!("XY"))"abXYZ"Ok(("Z", "ab"))
pairpair!(tag!("ab"), tag!("XY"))"abXYZ"Ok(("Z", ("ab", "XY")))
separated_pairseparated_pair!(tag!("hello"), char!(','), tag!("world"))"hello,world!"Ok(("!", ("hello", "world")))
tupletuple!(tag!("ab"), tag!("XY"), take!(1))"abXYZ!"Ok(("!", ("ab", "XY", "Z")))Chains parsers and assemble the sub results in a tuple. You can use as many child parsers as you can put elements in a tuple
do_parsedo_parse!(tag: take!(2) >> length: be_u8 >> data: take!(length) >> (Buffer { tag: tag, data: data}) )&[0, 0, 3, 1, 2, 3][..]Buffer { tag: &[0, 0][..], data: &[1, 2, 3][..] }do_parse applies sub parsers in a sequence. It can store intermediary results and make them available for later parsers

6.4 Applying a parser multiple times

combinatorusageinputoutputcomment
countcount!(take!(2), 3)"abcdefgh"Ok(("gh", vec!("ab", "cd", "ef")))Applies the child parser a specified number of times
many0many0!(tag!("ab"))"abababc"Ok(("c", vec!("ab", "ab", "ab")))Applies the parser 0 or more times and returns the list of results in a Vec. many1 does the same operation but must return at least one element
many_m_nmany_m_n!(1, 3, tag!("ab"))"ababc"Ok(("c", vec!("ab", "ab")))Applies the parser between m and n times (n included) and returns the list of results in a Vec
many_tillmany_till!(tag!( "ab" ), tag!( "ef" ))"ababefg"Ok(("g", (vec!("ab", "ab"), "ef")))Applies the first parser until the second applies. Returns a tuple containing the list of results from the first in a Vec and the result of the second
separated_listseparated_list!(tag!(","), tag!("ab"))"ab,ab,ab."Ok((".", vec!("ab", "ab", "ab")))separated_nonempty_list works like separated_list but must returns at least one element
fold_many0fold_many0!(be_u8, 0, \|acc, item\| acc + item)[1, 2, 3]Ok(([], 6))Applies the parser 0 or more times and folds the list of return values. The fold_many1 version must apply the child parser at least one time
fold_many_m_nfold_many_m_n!(1, 2, be_u8, 0, \|acc, item\| acc + item)[1, 2, 3]Ok(([3], 3))Applies the parser between m and n times (n included) and folds the list of return value
length_countlength_count!(number, tag!("ab"))"2ababab"Ok(("ab", vec!("ab", "ab")))Gets a number from the first parser, then applies the second parser that many times

6.5 Integers

Parsing integers from binary formats can be done in two ways: With parser functions, or combinators with configurable endianness:

  • configurable endianness: i16!, i32!, i64!, u16!, u32!, u64! are combinators that take as argument a nom::Endianness, like this: i16!(endianness). If the parameter is nom::Endianness::Big, parse a big endian i16 integer, otherwise a little endian i16 integer.
  • fixed endianness: The functions are prefixed by be_ for big endian numbers, and by le_ for little endian numbers, and the suffix is the type they parse to. As an example, be_u32 parses a big endian unsigned integer stored in 32 bits.
  • be_f32, be_f64, le_f32, le_f64: Recognize floating point numbers
  • be_i8, be_i16, be_i24, be_i32, be_i64: Big endian signed integers
  • be_u8, be_u16, be_u24, be_u32, be_u64: Big endian unsigned integers
  • le_i8, le_i16, le_i24, le_i32, le_i64: Little endian signed integers
  • le_u8, le_u16, le_u24, le_u32, le_u64: Little endian unsigned integers
  • eof!: Returns its input if it is at the end of input data
  • complete!: Replaces an Incomplete returned by the child parser with an Error

6.7 Modifiers

  • cond!: Conditional combinator. Wraps another parser and calls it if the condition is met
  • flat_map!:
  • map!: Maps a function on the result of a parser
  • map_opt!: Maps a function returning an Option on the output of a parser
  • map_res!: Maps a function returning a Result on the output of a parser
  • not!: Returns a result only if the embedded parser returns Error or Incomplete. Does not consume the input
  • opt!: Make the underlying parser optional
  • opt_res!: Make the underlying parser optional
  • parse_to!: Uses the parse method from std::str::FromStr to convert the current input to the specified type
  • peek!: Returns a result without consuming the input
  • recognize!: If the child parser was successful, return the consumed input as the produced value
  • consumed(): If the child parser was successful, return a tuple of the consumed input and the produced output.
  • return_error!: Prevents backtracking if the child parser fails
  • tap!: Allows access to the parser's result without affecting it
  • verify!: Returns the result of the child parser if it satisfies a verification function

6.8 Error management and debugging

  • add_return_error!: Add an error if the child parser fails
  • dbg!: Prints a message if the parser fails
  • dbg_dmp!: Prints a message and the input if the parser fails
  • error_node_position!: Creates a parse error from a nom::ErrorKind, the position in the input and the next error in the parsing tree. If the verbose-errors feature is not activated, it defaults to only the error code
  • error_position!: Creates a parse error from a nom::ErrorKind and the position in the input. If the verbose-errors feature is not activated, it defaults to only the error code
  • fix_error!: Translate parser result from IResult to IResult with a custom type

6.9 Text parsing

  • escaped!: Matches a byte string with escaped characters
  • escaped_transform!: Matches a byte string with escaped characters, and returns a new string with the escaped characters replaced

6.10 Binary format parsing

  • length_data!: Gets a number from the first parser, then takes a subslice of the input of that size, and returns that subslice
  • length_bytes!: Alias for length_data
  • length_value!: Gets a number from the first parser, takes a subslice of the input of that size, then applies the second parser on that subslice. If the second parser returns Incomplete, length_value! will return an error

6.11 Bit stream parsing

  • bits!: Transforms the current input type (byte slice &[u8]) to a bit stream on which bit specific parsers and more general combinators can be applied
  • bytes!: Transforms its bits stream input back into a byte slice for the underlying parser
  • tag_bits!: Matches an integer pattern to a bitstream. The number of bits of the input to compare must be specified
  • take_bits!: Generates a parser consuming the specified number of bits

6.12 Remaining combinators

  • apply!: Emulate function currying: apply!(my_function, arg1, arg2, ...) becomes my_function(input, arg1, arg2, ...)
  • call!: Used to wrap common expressions and function as macros
  • method!: Makes a method from a parser combination
  • named!: Makes a function from a parser combination
  • named_args!: Makes a function from a parser combination with arguments
  • named_attr!: Makes a function from a parser combination, with attributes
  • try_parse!: A bit like std::try!, this macro will return the remaining input and parsed value if the child parser returned Ok, and will do an early return for Error and Incomplete. This can provide more flexibility than do_parse! if needed
  • success: Returns a value without consuming any input, always succeeds

6.13 Character test functions

Use these functions with a combinator like take_while!:

  • is_alphabetic: Tests if byte is ASCII alphabetic: [A-Za-z]
  • is_alphanumeric: Tests if byte is ASCII alphanumeric: [A-Za-z0-9]
  • is_digit: Tests if byte is ASCII digit: [0-9]
  • is_hex_digit: Tests if byte is ASCII hex digit: [0-9A-Fa-f]
  • is_oct_digit: Tests if byte is ASCII octal digit: [0-7]
  • is_space: Tests if byte is ASCII space or tab: [ \t]
  • alpha: Recognizes one or more lowercase and uppercase alphabetic characters: [a-zA-Z]
  • alphanumeric: Recognizes one or more numerical and alphabetic characters: [0-9a-zA-Z]
  • anychar:
  • begin:
  • crlf:
  • digit: Recognizes one or more numerical characters: [0-9]
  • double: Recognizes floating point number in a byte string and returns a f64
  • eol:
  • float: Recognizes floating point number in a byte string and returns a f32
  • hex_digit: Recognizes one or more hexadecimal numerical characters: [0-9A-Fa-f]
  • hex_u32: Recognizes a hex-encoded integer
  • line_ending: Recognizes an end of line (both \n and \r\n)
  • multispace: Recognizes one or more spaces, tabs, carriage returns and line feeds
  • newline: Matches a newline character \n
  • non_empty: Recognizes non empty buffers
  • not_line_ending:
  • oct_digit: Recognizes one or more octal characters: [0-7]
  • rest: Return the remaining input
  • shift:
  • sized_buffer:
  • space: Recognizes one or more spaces and tabs
  • tab: Matches a tab character \t