39 lines
1.0 KiB
Go
39 lines
1.0 KiB
Go
// In this example, we show that any type can be extended into a parser,
|
|
// filling that type with data from the ParseHandler methods.
|
|
//
|
|
// Here, we create a custom type 'Chunks', which is an alias
|
|
// for []string. We add a ParseHandler method directly to that type
|
|
// and let the parsing code fill the slice with strings during parsing.
|
|
|
|
package examples
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"git.makaay.nl/mauricem/go-parsekit"
|
|
)
|
|
|
|
type Chunks []string
|
|
|
|
func (l *Chunks) AddChopped(s string, chunkSize int) *parsekit.Error {
|
|
c, a := parsekit.C, parsekit.A
|
|
chunkOfRunes := c.MinMax(1, chunkSize, a.AnyRune)
|
|
|
|
parser := parsekit.NewParser(func(p *parsekit.ParseAPI) {
|
|
for p.On(chunkOfRunes).Accept() {
|
|
*l = append(*l, p.Result().String())
|
|
}
|
|
})
|
|
return parser.Execute(s)
|
|
}
|
|
|
|
func Example_usingSliceAsParserState() {
|
|
chunks := &Chunks{}
|
|
chunks.AddChopped("123412341234xxx", 4)
|
|
chunks.AddChopped("1234567812345678xxxxx", 8)
|
|
|
|
fmt.Printf("Matches = %q", *chunks)
|
|
// Output:
|
|
// Matches = ["1234" "1234" "1234" "xxx" "12345678" "12345678" "xxxxx"]
|
|
}
|