forked from mbordner/kazaam
/
substr.go
64 lines (51 loc) · 1.29 KB
/
substr.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
package converter
import (
"errors"
"regexp"
"strconv"
"github.com/semarcial/kazaam/v5/transform"
)
type Substr struct {
ConverterBase
}
// |substr start end , end is optional, and will be the last char sliced's index + 1,
// start is the start index and required
func (c *Substr) Convert(jsonData []byte, value []byte, args []byte) (newValue []byte, err error) {
newValue = value
var jsonValue, argsValue *transform.JSONValue
jsonValue, err = c.NewJSONValue(value)
if err != nil {
return
}
argsValue, err = transform.NewJSONValue(args)
if err != nil {
return
}
if jsonValue.IsString() == false || argsValue.IsString() == false {
err = errors.New("invalid value or arguments for substr converter")
return
}
var re *regexp.Regexp
re, err = regexp.Compile(`(?:\s*)(\d+)(?:\s*)(\d+)*(?:\s*)`)
if err != nil {
return
}
argsString := argsValue.GetStringValue()
origValue := jsonValue.GetStringValue()
var start, end int64
end = int64(len(origValue))
if matches := re.FindStringSubmatch(argsString); matches != nil {
start, err = strconv.ParseInt(matches[1], 10, 64)
if err != nil {
return
}
if len(matches) > 2 {
end, err = strconv.ParseInt(matches[2], 10, 64)
if err != nil {
return
}
}
}
newValue = []byte(strconv.Quote(origValue[start:end]))
return
}