Function nom_supreme::multi::collect_separated_terminated
source · [−]pub fn collect_separated_terminated<Input, ParseOutput, SepOutput, TermOutput, ParseErr, Collection>(
parser: impl Parser<Input, ParseOutput, ParseErr>,
separator: impl Parser<Input, SepOutput, ParseErr>,
terminator: impl Parser<Input, TermOutput, ParseErr>
) -> impl Parser<Input, Collection, ParseErr> where
Input: Clone + InputLength,
ParseErr: ParseError<Input>,
Collection: Default + Extend<ParseOutput>,
Expand description
Parse a series of 1 or more things, separated by separator
, terminated by
terminator
, and collect them into a collection using Extend
.
When this parser is run, it will create a new, empty collection with
Default
. It will then collect each parsed item into the collection with
Extend
. See the module docs for details of how this parser parses a sequence.
See the module docs for a detailed description of how this parser parses a sequence.
Example
use nom_supreme::{
multi::collect_separated_terminated,
parser_ext::ParserExt,
error::ErrorTree,
};
use nom::character::complete::{digit1, char, space0};
use nom::{IResult, Parser, error::ParseError};
fn parse_number(input: &str) -> IResult<&str, i32, ErrorTree<&str>> {
digit1
.preceded_by(char('-').opt())
.recognize()
.parse_from_str()
.parse(input)
}
// A vector is a square brackets, containing comma separated numbers, with
// whitespace in between
let mut vec_parser = collect_separated_terminated(
// Parse numbers
parse_number.terminated(space0),
// separated by commas
char(',').terminated(space0),
// terminated by a close bracket
char(']'),
)
// Allow for empty vectors
.or(char(']').value(Vec::new()))
.preceded_by(char('[').terminated(space0));
let result: IResult<&str, Vec<i32>, ErrorTree<&str>> = vec_parser.parse("[1, 2, -3, 4]");
let vec = result.unwrap().1;
assert_eq!(vec, [1, 2, -3, 4]);