package re import ( "errors" "fmt" "io" "regexp" "strings" lru "github.com/hashicorp/golang-lru" ) var errNotRE = errors.New("not re") type RE struct { last *lru.Cache w io.Writer } func NewRE(w io.Writer) *RE { last, _ := lru.New(100) return &RE{last: last, w: w} } func (r *RE) Replace(text, nick string) { defer r.last.Add(nick, text) if !strings.HasPrefix(text, "s") { return } if tofix, ok := r.last.Get(nick); ok { global := strings.HasSuffix(text, "g") fixed, err := Replace(tofix.(string), text[1:], global) if err == nil && fixed != tofix { fmt.Fprintf(r.w, "%v meant to say: %s", nick, fixed) } } } 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 }