This is part of a series of posts documenting Sprache:
- Sprache Part 1: Parsing Characters
- Sprache Part 2: Parsing Strings
- Sprache Part 3: Repetition (Many, AtLeastOnce, Until, Repeat, Once)
- Sprache Part 4: Or and XOr
- Sprache Part 5: Select, Return, and Regex
- Sprache Part 6: DelimitedBy
- Sprache Part 7: ChainOperator and ChainRightOperator
- Sprache Part 8: Token, Contained, Identifier, LineTerminator
- Sprache Part 9: Positioned
DelimitedBy methods are helpers for parsing delimited sequences of elements, (like arrays
[1,2,3]) with a cleaner syntax.
Parses elements matched by
parser, delimited by elements matched by
Parser<IEnumerable<T>> DelimitedBy<T, U>(this Parser<T> parser, Parser<U> delimiter)
The following example parses a structure that looks a bit like generics type specifiers in C#:
Note that trailing delimiters are not matched, and that the element must be matched at least once, which is where
Optional comes in handy:
Parses delimited elements, failing if any delimited element is only partially matched.
Parser<IEnumerable<T>> XDelimitedBy<T, U>(this Parser<T> itemParser, Parser<U> delimiter)
Like all of the
X variants, this is intended to improve error handling by failing early, however the difference is subtle. This example shows the difference in behaviour between
What its looking for is where the combination of the delimiter + item only partially matched:
- When parsing “1, 2, "
DelimitedBysucceeded because it matched a delimiter, but did not match an item.
- When parsing “1, 2a, 3” however, both methods successfully matches a delimiter and an element “, 2” and stop parsing.
- Finally, when parsing “1, 2 "
XDelimitedByrecognises the whitespace as a partial match on the delimiter, and so fails.
Author Justin Pealing