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
This post covers
Return, which are used for transforming the result of parsing, e.g. into an abstract syntax tree, as well as
RegexMatch, which as you might expect allow you to augment Sprache parsers with regular expressions.
Take the result of parsing, and project it onto a different domain:
Parser<U> Select<T, U>(this Parser<T> parser, Func<T, U> convert)
This example takes the parser
Number, which outputs a string, and converts it into a parser which produces integers using
This method is also used extensively when parsing using linq expressions, for example in the following example which parses an XML element, select is used both to concatenate the to parsed parts of the identifier, and to return the tag name.
Succeed immediately and return value, a bit like select, but ignorings the result of the parser. It has two overloads, but I’m honestly not sure when you would use the first:
Parser<T> Return<T>(T value)
Parser<U> Return<T, U>(this Parser<T> parser, U value)
Although similar to
Select, this is handy to use in situations where the return value from the parser doesn’t matter, e.g when parsing operators or keywords.
Construct a parser from the given regular expression. Has 2 overloads allowing you to supply the regex as either a
string or a
Regex object. Like
Char, this also lets you supply a description for the parser.
Parser<string> Regex(string pattern, string description = null)
Parser<string> Regex(Regex regex, string description = null)
Construct a parser from the given regular expression, however differs from
Regex in that it returns the
Match object returned by the regular expression instead of the matched value.
Parser<Match> RegexMatch(string pattern, string description = null)
Parser<Match> RegexMatch(Regex regex, string description = null)
Author Justin Pealing