-
-
Save samarpw/d67d0638ac30ed1005a750d62e91d077 to your computer and use it in GitHub Desktop.
Capturing grouping for regex function replace in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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:] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment