Function winnow::combinator::separated

source ·
pub fn separated<I, O, C, O2, E, P, S>(
    range: impl Into<Range>,
    parser: P,
    separator: S
) -> impl Parser<I, C, E>
where I: Stream, C: Accumulate<O>, P: Parser<I, O, E>, S: Parser<I, O2, E>, E: ParserError<I>,
Expand description

Accumulate the output of a parser, interleaved with sep

This stops when either parser returns ErrMode::Backtrack. To instead chain an error up, see cut_err.

§Arguments

  • range The minimum and maximum number of iterations.
  • parser The parser that parses the elements of the list.
  • sep The parser that parses the separator between list elements.

Warning: If the separator parser accepts empty inputs (like alpha0 or digit0), separated will return an error, to prevent going into an infinite loop.

§Example

Zero or more repetitions:

use winnow::combinator::separated;
use winnow::token::tag;

fn parser(s: &str) -> IResult<&str, Vec<&str>> {
  separated(0.., "abc", "|").parse_peek(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(""), Ok(("", vec![])));
assert_eq!(parser("def|abc"), Ok(("def|abc", vec![])));

One or more repetitions:

use winnow::combinator::separated;
use winnow::token::tag;

fn parser(s: &str) -> IResult<&str, Vec<&str>> {
  separated(1.., "abc", "|").parse_peek(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(ErrMode::Backtrack(InputError::new("", ErrorKind::Tag))));
assert_eq!(parser("def|abc"), Err(ErrMode::Backtrack(InputError::new("def|abc", ErrorKind::Tag))));

Fixed number of repetitions:

use winnow::combinator::separated;
use winnow::token::tag;

fn parser(s: &str) -> IResult<&str, Vec<&str>> {
  separated(2, "abc", "|").parse_peek(s)
}

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

Arbitrary repetitions:

use winnow::combinator::separated;
use winnow::token::tag;

fn parser(s: &str) -> IResult<&str, Vec<&str>> {
  separated(0..=2, "abc", "|").parse_peek(s)
}

assert_eq!(parser("abc|abc|abc"), Ok(("|abc", vec!["abc", "abc"])));
assert_eq!(parser("abc123abc"), Ok(("123abc", vec!["abc"])));
assert_eq!(parser("abc|def"), Ok(("|def", vec!["abc"])));
assert_eq!(parser(""), Ok(("", vec![])));
assert_eq!(parser("def|abc"), Ok(("def|abc", vec![])));