summaryrefslogtreecommitdiff
path: root/internal/re/re.go
blob: b235282278bdf97215afb3e76fe6b2acbb51226c (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
package re

import (
	"errors"
	"regexp"
	"strings"
)

var errNotRE = errors.New("not re")

func Replace(s, r string, global bool) (string, error) {
	// min: at least two separators
	if len(r) < 2 {
		return "", errNotRE
	}
	z := strings.Split(r[1:], string(r[0]))
	// match // and ///
	if len(z) < 2 || len(z) > 3 {
		return "", errNotRE
	}
	re, err := regexp.Compile(z[0])
	if err != nil {
		return "", err
	}
	i := 1
	if global {
		i = -1
	}
	return re.ReplaceAllStringFunc(s, func(b string) string {
		if i != 0 {
			i--
			return z[1]
		}
		return b
	}), nil
}