Skip to content

Instantly share code, notes, and snippets.

@elliotchance

elliotchance/example.go

Last active Sep 17, 2020
Embed
What would you like to do?
Capturing grouping for regex function replace in Go
func main() {
str := "abc foo:bar def baz:qux ghi"
re := regexp.MustCompile("([a-z]+):([a-z]+)")
result := ReplaceAllStringSubmatchFunc(re, str, func(groups []string) string {
return groups[1] + "." + groups[2]
})
fmt.Printf("'%s'\n", result)
}
import "regexp"
func ReplaceAllStringSubmatchFunc(re *regexp.Regexp, str string, repl func([]string) string) string {
result := ""
lastIndex := 0
for _, v := range re.FindAllSubmatchIndex([]byte(str), -1) {
groups := []string{}
for i := 0; i < len(v); i += 2 {
groups = append(groups, str[v[i]:v[i+1]])
}
result += str[lastIndex:v[0]] + repl(groups)
lastIndex = v[1]
}
return result + str[lastIndex:]
}
@vruzin

This comment has been minimized.

Copy link

@vruzin vruzin commented Sep 17, 2020

bad function ))
change

groups = append(groups, str[v[i]:v[i+1]])

on

if(v[i]==-1 || v[i+1] == -1) {
	groups = append(groups, "")
}else{
	groups = append(groups, str[v[i]:v[i+1]])
}

Otherwise, if the group is not found, there will be an error.
For example:
(?:aa(xxx)bbb)?(yyy)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment