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

import (
	"regexp"
	"strings"
)

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