nom::multi

Function separated_list1

Source
pub fn separated_list1<I, O, O2, E, F, G>(
    sep: G,
    f: F,
) -> impl FnMut(I) -> IResult<I, Vec<O>, E>
where I: Clone + InputLength, F: Parser<I, O, E>, G: Parser<I, O2, E>, E: ParseError<I>,
Expand description

Alternates between two parsers to produce a list of elements until Err::Error.

Fails if the element parser does not produce at least one element.$

This stops when either parser returns Err::Error and returns the results that were accumulated. To instead chain an error up, see cut.

ยงArguments

  • sep Parses the separator between list elements.
  • f Parses the elements of the list.
use nom::multi::separated_list1;
use nom::bytes::complete::tag;

fn parser(s: &str) -> IResult<&str, Vec<&str>> {
  separated_list1(tag("|"), tag("abc"))(s)
}

assert_eq!(parser("abc|abc|abc"), Ok(("", vec!["abc", "abc", "abc"])));
assert_eq!(parser("abc123abc"), Ok(("123abc", vec!["abc"])));
assert_eq!(parser("abc|def"), Ok(("|def", vec!["abc"])));
assert_eq!(parser(""), Err(Err::Error(Error::new("", ErrorKind::Tag))));
assert_eq!(parser("def|abc"), Err(Err::Error(Error::new("def|abc", ErrorKind::Tag))));