40 lines
1.0 KiB
Go
40 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 Handler methods.
|
|
//
|
|
// Here, we create a custom type 'Chunks', which is an alias
|
|
// for []string. We add a Handler method directly to that type
|
|
// and let the parsing code append items to the slice during parsing.
|
|
|
|
package examples
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"git.makaay.nl/mauricem/go-parsekit/parse"
|
|
"git.makaay.nl/mauricem/go-parsekit/tokenize"
|
|
)
|
|
|
|
type Chunks []string
|
|
|
|
func (l *Chunks) AddChopped(s string, chunkSize int) error {
|
|
c, a := tokenize.C, tokenize.A
|
|
chunkOfRunes := c.MinMax(1, chunkSize, a.AnyRune)
|
|
|
|
parseChunks := parse.New(func(p *parse.API) {
|
|
for p.Accept(chunkOfRunes) {
|
|
*l = append(*l, p.Result.String())
|
|
}
|
|
})
|
|
return parseChunks(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"]
|
|
}
|