summaryrefslogtreecommitdiff
path: root/internal/funcs/regexp.go
blob: 6da1190c750905dfa0f96a54b522d25b62719bf3 (plain)
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
83
84
85
86
87
88
89
90
package funcs

import (
	"context"
	"fmt"

	"github.com/hairyhenderson/gomplate/v4/conv"
	"github.com/hairyhenderson/gomplate/v4/regexp"
)

// CreateReFuncs -
func CreateReFuncs(ctx context.Context) map[string]interface{} {
	ns := &ReFuncs{ctx}
	return map[string]interface{}{
		"regexp": func() interface{} { return ns },
	}
}

// ReFuncs -
type ReFuncs struct {
	ctx context.Context
}

// Find -
func (ReFuncs) Find(re, input interface{}) (string, error) {
	return regexp.Find(conv.ToString(re), conv.ToString(input))
}

// FindAll -
func (ReFuncs) FindAll(args ...interface{}) ([]string, error) {
	re := ""
	n := 0
	input := ""
	switch len(args) {
	case 2:
		n = -1
		re = conv.ToString(args[0])
		input = conv.ToString(args[1])
	case 3:
		re = conv.ToString(args[0])
		n = conv.ToInt(args[1])
		input = conv.ToString(args[2])
	default:
		return nil, fmt.Errorf("wrong number of args: want 2 or 3, got %d", len(args))
	}
	return regexp.FindAll(re, n, input)
}

// Match -
func (ReFuncs) Match(re, input interface{}) bool {
	return regexp.Match(conv.ToString(re), conv.ToString(input))
}

// QuoteMeta -
func (ReFuncs) QuoteMeta(in interface{}) string {
	return regexp.QuoteMeta(conv.ToString(in))
}

// Replace -
func (ReFuncs) Replace(re, replacement, input interface{}) string {
	return regexp.Replace(conv.ToString(re),
		conv.ToString(replacement),
		conv.ToString(input))
}

// ReplaceLiteral -
func (ReFuncs) ReplaceLiteral(re, replacement, input interface{}) (string, error) {
	return regexp.ReplaceLiteral(conv.ToString(re),
		conv.ToString(replacement),
		conv.ToString(input))
}

// Split -
func (ReFuncs) Split(args ...interface{}) ([]string, error) {
	re := ""
	n := -1
	input := ""
	switch len(args) {
	case 2:
		re = conv.ToString(args[0])
		input = conv.ToString(args[1])
	case 3:
		re = conv.ToString(args[0])
		n = conv.ToInt(args[1])
		input = conv.ToString(args[2])
	default:
		return nil, fmt.Errorf("wrong number of args: want 2 or 3, got %d", len(args))
	}
	return regexp.Split(re, n, input)
}