Home > Article > Backend Development > How to correctly replace strings in golang with "greedy principle"?
I tried to mask the string, but something went wrong
The reproducible code is as follows and requires all old and new pairs, how to get col1
instead of col0b
?
package main import ( "fmt" "strings" ) func main() { r := strings.NewReplacer("a", "col0", "ab", "col1") s := "ab" fmt.Println(r.Replace(s)) }
I hope that the string can be replaced using the maximum length or greedy principle
According to documentation, NewReplacer's replacement is as per their The strings are executed in the order they appear in the target, with no overlapping matches, so it will always follow the basis of the first match. If allowed, I think you could fix this by reorganizing the replacement pairs so that the longer string ("ab"-"col1"
) is placed inside the shorter string ( "a","col0"
)before
package main import ( "fmt" "strings" ) func main() { r := strings.NewReplacer("ab", "col1", "a", "col0") s := "ab" fmt.Println(r.Replace(s)) }
The above is the detailed content of How to correctly replace strings in golang with "greedy principle"?. For more information, please follow other related articles on the PHP Chinese website!