-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlib.go
81 lines (70 loc) · 1.82 KB
/
lib.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package rgx
// Compile compiles the given regex string
func Compile(regexString string) (*State, *RegexError) {
parseContext := parsingContext{
pos: 0,
tokens: []regexToken{},
capturedGroups: map[string]bool{},
}
if err := parse(regexString, &parseContext); err != nil {
return nil, err
}
return toNfa(&parseContext)
}
// Test checks if the given input string conforms to this NFA
func (s *State) Test(inputString string) Result {
checkContext := ®exCheckContext{
groups: map[string]*capture{},
}
result := s.check(inputString, -1, s.startOfText, checkContext)
// prepare the result
groups := map[string]string{}
if result {
// extract strings from the groups
for groupName, captured := range checkContext.groups {
groups[groupName] = captured.string(inputString)
}
}
return Result{
Matches: result,
Groups: groups,
}
}
func (s *State) FindMatches(inputString string) []Result {
var results []Result
start := -1
for start < len(inputString) {
checkContext := ®exCheckContext{
groups: map[string]*capture{},
}
result := s.check(inputString, start, s.startOfText, checkContext)
if !result {
break
}
// prepare the result
groups := map[string]string{}
if result {
// extract strings from the groups
for groupName, captured := range checkContext.groups {
groups[groupName] = captured.string(inputString)
if groupName == "0" {
start = captured.end + 1
}
}
}
r := Result{
Matches: result,
Groups: groups,
}
results = append(results, r)
}
return results
}
// Check compiles the regexString and tests the inputString against it
func Check(regexString string, inputString string) (Result, *RegexError) {
compiledNfa, err := Compile(regexString)
if err != nil {
return Result{}, err
}
return compiledNfa.Test(inputString), nil
}