forked from gookit/goutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
50 lines (41 loc) · 819 Bytes
/
parser.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package textscan
import (
"bytes"
"io"
"strings"
)
// HandleFn for token
type HandleFn func(t Token)
// Parser struct
type Parser struct {
ts *TextScanner
// Func for handle tokens
Func HandleFn
}
// NewParser instance
func NewParser(fn HandleFn) *Parser {
return &Parser{
Func: fn,
ts: &TextScanner{},
}
}
// AddMatchers register token matchers
func (p *Parser) AddMatchers(ms ...Matcher) {
p.ts.AddMatchers(ms...)
}
// Parse input bytes
func (p *Parser) Parse(bs []byte) error {
return p.ParseFrom(bytes.NewReader(bs))
}
// ParseText input string
func (p *Parser) ParseText(text string) error {
return p.ParseFrom(strings.NewReader(text))
}
// ParseFrom input reader
func (p *Parser) ParseFrom(r io.Reader) error {
ts := NewScanner(r)
for ts.Scan() {
p.Func(ts.Token())
}
return nil
}