Function winnow::combinator::alt
source · pub fn alt<Input: Stream, Output, Error, Alternatives>(
alternatives: Alternatives,
) -> impl Parser<Input, Output, Error>where
Alternatives: Alt<Input, Output, Error>,
Error: ParserError<Input>,
Expand description
Pick the first successful parser
To stop on an error, rather than trying further cases, see
cut_err
([example][crate::_tutorial::chapter_7]).
For tight control over the error when no match is found, add a final case using fail
.
Alternatively, with a [custom error type][crate::_topic::error], it is possible to track all
errors or return the error of the parser that went the farthest in the input data.
When the alternative cases have unique prefixes, dispatch
can offer better performance.
§Example
use winnow::ascii::{alpha1, digit1};
use winnow::combinator::alt;
fn parser(input: &str) -> IResult<&str, &str> {
alt((alpha1, digit1)).parse_peek(input)
};
// the first parser, alpha1, takes 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(ErrMode::Backtrack(InputError::new(" ", ErrorKind::Slice))));