This repository has been archived by the owner on Mar 20, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
pattern.go
82 lines (72 loc) · 1.53 KB
/
pattern.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
82
package cc
import (
"regexp"
"github.com/damnever/cc/rpn"
)
// Pattern implements the Patterner interface.
type Pattern struct {
pattern string
re *regexp.Regexp
rpn *rpn.ReversePolishNotation
err error
badRe bool
badCond bool
}
// NewPattern creates a new Pattern, even if pattern is not valid,
// in such case, Validate-like methods always return false.
// The compiled pattern is cached.
func NewPattern(pattern string) *Pattern {
return &Pattern{
pattern: pattern,
re: nil,
rpn: nil,
err: nil,
badRe: false,
badCond: false,
}
}
// Err returns the error if pattern is wrong.
func (p *Pattern) Err() error {
return p.err
}
// ValidateInt validate the int value n, return true if it is valid.
func (p *Pattern) ValidateInt(n int) bool {
return p.ValidateFloat(float64(n))
}
// ValidateFloat validate the float64 value n, return true if it is valid.
func (p *Pattern) ValidateFloat(n float64) bool {
if p.badCond {
return false
}
if p.rpn == nil {
rpn, err := rpn.New(p.pattern)
if err != nil {
p.err = err
p.badCond = true
return false
}
p.rpn = rpn
}
res, err := p.rpn.Calculate(n)
if err != nil {
p.err = err
p.badCond = true
}
return res
}
// ValidateString validate the string value n, return true if it is valid.
func (p *Pattern) ValidateString(s string) bool {
if p.badRe {
return false
}
if p.re == nil {
re, err := regexp.Compile(p.pattern)
if err != nil {
p.err = err
p.badRe = true
return false
}
p.re = re
}
return p.re.MatchString(s)
}