我试图用字符串
中确定的数字范围替换带随机数的字符串package main
import (
"fmt"
"math/rand"
"regexp"
"strconv"
)
func replaceFunc(s string) string {
groups := //?? How do i get the current mach groups
return rand.Intn( groups[2] - groups[1]) + groups[1]
}
func main() {
rand.Seed(time.Now().Unix())
repl := "1,10 1,50 1,12 1,2 1,3"
repl = regexp.MustCompile("(\\d+),(\\d+)").ReplaceAllStringFunc(repl, replaceFunc)
fmt.Println(repl)
}
替换时如何获取正则表达式组?
答案 0 :(得分:1)
您将单独获得每个匹配项作为函数的参数(replaceFunc
将在每次匹配时调用一次,但不会每个组调用一次。)
您可以使用strings.Split
拆分数字,然后将它们转换为整数:
https://play.golang.org/p/ks0tkMQ2TY
func replaceFunc(s string) string {
pieces:= strings.Split(s, ",")
a,_ := strconv.Atoi(pieces[0])
b,_ := strconv.Atoi(pieces[1])
return strconv.Itoa(rand.Intn( b - a) + a)
}
func main() {
rand.Seed(time.Now().Unix())
repl := "1,10 1,50 1,12 1,2 1,3"
repl = regexp.MustCompile("(\\d+),(\\d+)").ReplaceAllStringFunc(repl, replaceFunc)
fmt.Println(repl)
}