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

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

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

func re(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 -= 1
			return z[1]
		}
		return b
	}), nil
}