summaryrefslogtreecommitdiff
path: root/internal/re/re.go
diff options
context:
space:
mode:
Diffstat (limited to 'internal/re/re.go')
-rw-r--r--internal/re/re.go36
1 files changed, 36 insertions, 0 deletions
diff --git a/internal/re/re.go b/internal/re/re.go
new file mode 100644
index 0000000..b235282
--- /dev/null
+++ b/internal/re/re.go
@@ -0,0 +1,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
+}