package main
import (
"fmt"
"strings"
)
const refString = "Mary had a little lamb"
const refStringTwo = "lamb lamb lamb lamb"
func main() {
out := strings.Replace(refString, "lamb", "wolf", -1)
fmt.Println(out)
out = strings.Replace(refStringTwo, "lamb", "wolf", 2)
fmt.Println(out)
}
/*
Mary had a little wolf
wolf wolf lamb lamb
*/
package main
import (
"fmt"
"strings"
)
const refString = "Mary had a little lamb"
func main() {
replacer := strings.NewReplacer("lamb", "wolf", "Mary", "Jack")
out := replacer.Replace(refString)
fmt.Println(out)
}
/*
Jack had a little wolf
*/
正则替换
package main
import (
"fmt"
"regexp"
)
const refString = "Mary had a little lamb"
func main() {
regex := regexp.MustCompile("l[a-z]+")
out := regex.ReplaceAllString(refString, "replacement")
fmt.Println(out)
}
/*
Mary had a replacement replacement
*/