-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvmregex.go
48 lines (42 loc) · 1.02 KB
/
vmregex.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
// Package vmregex provides a VM regex engine(VM engine).
package vmregex
import (
"github.com/8ayac/vm-regex-engine/parser"
"github.com/8ayac/vm-regex-engine/vm"
"github.com/8ayac/vm-regex-engine/vm/instruction"
"github.com/8ayac/vm-regex-engine/vm/opcode"
)
// Regexp has a VM and regexp string.
type Regexp struct {
regexp string
runtime *vm.VM
}
// NewRegexp return a new Regexp.
func NewRegexp(re string) *Regexp {
psr := parser.NewParser(re)
ast := psr.GetAST()
bc := ast.Compile()
bc.AddInst(instruction.NewInst(opcode.Match, 0, nil, nil), bc.N)
bc.Optimize()
return &Regexp{
regexp: re,
runtime: vm.NewVM(bc),
}
}
// Compile is a wrapper function of NewRegexp().
func Compile(re string) *Regexp {
return NewRegexp(re)
}
// Match returns whether the input string matches the regular expression.
func (re *Regexp) Match(s string) (start, end int) {
result := 0
for i := 0; i < len(s); i++ {
result = re.runtime.Run(s[i:] + "\x00")
if result != -1 {
start = i
end = result + i
return
}
}
return
}