59 lines
1.9 KiB
Go
59 lines
1.9 KiB
Go
// In this example, a parser is created that is able to parse input that looks
|
|
// like "Hello, <name>!", and that extracts the name from it.
|
|
//
|
|
// The implementation uses only a Matcher function and does not implement a
|
|
// full-fledged state-based Parser for it. If you want to see the same kind of
|
|
// functionality, implementated using a Paser, take a look at the
|
|
// HelloWorldUsingParser example.
|
|
package parsekit_test
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"git.makaay.nl/mauricem/go-parsekit"
|
|
)
|
|
|
|
func createHelloMatcher() *parsekit.MatcherWrapper {
|
|
// Easy access to parsekit definition.
|
|
c, a, m := parsekit.C, parsekit.A, parsekit.M
|
|
|
|
// Using the parser/combinator support of parsekit, we create a Matcher function
|
|
// that does all the work. The 'greeting' Matcher matches the whole input and
|
|
// drops all but the name from it.
|
|
hello := c.StrNoCase("hello")
|
|
comma := c.Seq(c.Opt(a.Whitespace), a.Comma, c.Opt(a.Whitespace))
|
|
separator := c.Any(comma, a.Whitespace)
|
|
name := c.OneOrMore(c.Not(a.Excl))
|
|
greeting := c.Seq(m.Drop(hello), m.Drop(separator), name, m.Drop(a.Excl))
|
|
|
|
// Using 'greeting' we can now create the Matcher-based parser.
|
|
return parsekit.NewMatcher(greeting, "a friendly greeting")
|
|
}
|
|
|
|
func Example_helloWorldUsingMatcher() {
|
|
parser := createHelloMatcher()
|
|
|
|
for i, input := range []string{
|
|
"Hello, world!",
|
|
"HELLO ,Johnny!",
|
|
"hello , Bob123!",
|
|
"hello Pizza!",
|
|
"Oh no!",
|
|
"Hello, world",
|
|
} {
|
|
output, err, ok := parser.Parse(input)
|
|
if !ok {
|
|
fmt.Printf("[%d] Input: %q Error: %s\n", i, input, err)
|
|
} else {
|
|
fmt.Printf("[%d] Input: %q Output: %s\n", i, input, output)
|
|
}
|
|
}
|
|
// Output:
|
|
// [0] Input: "Hello, world!" Output: world
|
|
// [1] Input: "HELLO ,Johnny!" Output: Johnny
|
|
// [2] Input: "hello , Bob123!" Output: Bob123
|
|
// [3] Input: "hello Pizza!" Output: Pizza
|
|
// [4] Input: "Oh no!" Error: unexpected character 'O' (expected a friendly greeting)
|
|
// [5] Input: "Hello, world" Error: unexpected character 'H' (expected a friendly greeting)
|
|
}
|