| 1 |
package helpers |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"regexp" |
| 6 |
) |
| 7 |
|
| 8 |
const ( |
| 9 |
|
| 10 |
exactValueCaptureRegex = multilineFlag + `^\s*` + valueOptPrefix + `%s` + valueOptSuffix + `\s*$` |
| 11 |
|
| 12 |
|
| 13 |
exactKeyCaptureRegex = multilineFlag + `^\s*` + optDeclareKeyword + keyOptPrefix + `%s` + keyOptSuffix + `\s*$` |
| 14 |
) |
| 15 |
|
| 16 |
type ValueRegex struct { |
| 17 |
regex []*regexp.Regexp |
| 18 |
} |
| 19 |
|
| 20 |
func NewValueRegex(regex ...string) *ValueRegex { |
| 21 |
return newValueRegex(exactValueCaptureRegex, regex) |
| 22 |
} |
| 23 |
|
| 24 |
func NewKeyRegex(regex ...string) *ValueRegex { |
| 25 |
return newValueRegex(exactKeyCaptureRegex, regex) |
| 26 |
} |
| 27 |
|
| 28 |
func newValueRegex(format string, regex []string) *ValueRegex { |
| 29 |
s := make([]*regexp.Regexp, 0, len(regex)) |
| 30 |
for _, r := range regex { |
| 31 |
s = append(s, regexp.MustCompile(fmt.Sprintf(format, r))) |
| 32 |
} |
| 33 |
|
| 34 |
return &ValueRegex{ |
| 35 |
regex: s, |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
func (arr *ValueRegex) Match(in string) bool { |
| 40 |
for _, regex := range arr.regex { |
| 41 |
if regex.MatchString(in) { |
| 42 |
return true |
| 43 |
} |
| 44 |
} |
| 45 |
return false |
| 46 |
} |
| 47 |
|
| 48 |
func (arr *ValueRegex) Find(in string) string { |
| 49 |
for _, regex := range arr.regex { |
| 50 |
if res := regex.FindString(in); res != "" { |
| 51 |
return res |
| 52 |
} |
| 53 |
} |
| 54 |
return "" |
| 55 |
} |
| 56 |
|
| 57 |
func (arr *ValueRegex) FindAll(in string) []string { |
| 58 |
res := make([]string, 0) |
| 59 |
for _, regex := range arr.regex { |
| 60 |
currRes := regex.FindAllString(in, -1) |
| 61 |
res = append(res, currRes...) |
| 62 |
} |
| 63 |
return res |
| 64 |
} |