nom::branch

Function alt

Source
pub fn alt<List>(l: List) -> Choice<List>
Expand description

Tests a list of parsers one by one until one succeeds.

It takes as argument either a tuple or an array of parsers. If using a tuple, there is a maximum of 21 parsers. If you need more, it is possible to use an array.

use nom::character::complete::{alpha1, digit1};
use nom::branch::alt;
fn parser(input: &str) -> IResult<&str, &str> {
  alt((alpha1, digit1)).parse(input)
};

// the first parser, alpha1, recognizes the input
assert_eq!(parser("abc"), Ok(("", "abc")));

// the first parser returns an error, so alt tries the second one
assert_eq!(parser("123456"), Ok(("", "123456")));

// both parsers failed, and with the default error type, alt will return the last error
assert_eq!(parser(" "), Err(Err::Error(error_position!(" ", ErrorKind::Digit))));

With a custom error type, it is possible to have alt return the error of the parser that went the farthest in the input data