somthing like this
https://play.golang.org/p/Abeq2-FV7NW
import (
"fmt"
"regexp"
"strings"
)
func main() {
fmt.Println("Hello, 世界")
r := regexp.MustCompile(`^9(\d{10})$|^00(.*)$|^\+(.*)`)
fmt.Println(ReplaceAllStringGroup("93881231212", `1$1|$2|$3`, r))
fmt.Println(ReplaceAllStringGroup("0013881231212", `0$1|$2|$3`, r))
fmt.Println(ReplaceAllStringGroup("+13881231212", `0$1|$2|$3`, r))
fmt.Println(ReplaceAllStringGroup("-13881231212", `0$1|$2|$3`, r))
}
func ReplaceAllStringGroup(s string, repl string, r *regexp.Regexp) string {
splitted := strings.Split(repl, "|")
list := r.FindStringSubmatch(s)
if len(list) != len(splitted)+1 {
return "not matched"
}
for i, m := range list[1:] {
if m != "" {
return r.ReplaceAllString(s, splitted[i])
}
}
return "not matched"
}
pkg "regexp" not have function which allow many group replace, only have ReplaceAllString
// ReplaceAllString returns a copy of src, replacing matches of the Regexp
// with the replacement string repl. Inside repl, $ signs are interpreted as
// in Expand, so for instance $1 represents the text of the first submatch.
func (re *Regexp) ReplaceAllString(src, repl string) string {
n := 2
if strings.Contains(repl, "$") {
n = 2 * (re.numSubexp + 1)
}
b := re.replaceAll(nil, src, n, func(dst []byte, match []int) []byte {
return re.expand(dst, repl, nil, src, match)
})
return string(b)
}
I looking for way to do replace with additional option `1$1|$2|$3`
pkg "regexp" not have function which allow many group replace, only have ReplaceAllString