如何删除字符串模式和该模式后面的所有字符串?

例如 :


package main


import "fmt"


func main() {

    pattern := "helloworld."

    myString := "foo.bar.helloworld.qwerty.zxc.helloworld.asd"

    fmt.Println(removeFromPattern(pattern, myString))

}


func removeFromPattern(p, ms string) string {

    // I confused here (in efficient way)

}

想要的输出:


qwerty.zxc.helloworld.asd

我如何获得想要的输出,以及如何从中删除该pattern模式后面的第一个和所有字符串myString?


明月笑刀无情
浏览 141回答 3
3回答

qq_遁去的一_1

1-使用_, after, _ = strings.Cut(ms, p),试试这个:func removeFromPattern(p, ms string) (after string) {&nbsp; &nbsp; _, after, _ = strings.Cut(ms, p) // before and after sep.&nbsp; &nbsp; return}哪个用途strings.Index:// Cut slices s around the first instance of sep,// returning the text before and after sep.// The found result reports whether sep appears in s.// If sep does not appear in s, cut returns s, "", false.func Cut(s, sep string) (before, after string, found bool) {&nbsp; &nbsp; if i := Index(s, sep); i >= 0 {&nbsp; &nbsp; &nbsp; &nbsp; return s[:i], s[i+len(sep):], true&nbsp; &nbsp; }&nbsp; &nbsp; return s, "", false}2-使用strings.Index,试试这个:func removeFromPattern(p, ms string) string {&nbsp; &nbsp; i := strings.Index(ms, p)&nbsp; &nbsp; if i == -1 {&nbsp; &nbsp; &nbsp; &nbsp; return ""&nbsp; &nbsp; }&nbsp; &nbsp; return ms[i+len(p):]}3-使用strings.Split,试试这个:func removeFromPattern(p, ms string) string {&nbsp; &nbsp; a := strings.Split(ms, p)&nbsp; &nbsp; if len(a) != 2 {&nbsp; &nbsp; &nbsp; &nbsp; return ""&nbsp; &nbsp; }&nbsp; &nbsp; return a[1]}4-使用regexp,试试这个func removeFromPattern(p, ms string) string {&nbsp; &nbsp; a := regexp.MustCompile(p).FindStringSubmatch(ms)&nbsp; &nbsp; if len(a) < 2 {&nbsp; &nbsp; &nbsp; &nbsp; return ""&nbsp; &nbsp; }&nbsp; &nbsp; return a[1]}

杨__羊羊

strings.Split就够了func main() {&nbsp; &nbsp; pattern := "helloworld."&nbsp; &nbsp; myString := "foo.bar.helloworld.qwerty.zxc"&nbsp; &nbsp; res := removeFromPattern(pattern, myString)&nbsp; &nbsp; fmt.Println(res)}func removeFromPattern(p, ms string) string {&nbsp; &nbsp; parts := strings.Split(ms, p)&nbsp; &nbsp; if len(parts) > 1 {&nbsp; &nbsp; &nbsp; &nbsp; return parts[1]&nbsp; &nbsp; }&nbsp; &nbsp; return ""}

潇湘沐

func removeFromPattern(p, ms string) string {&nbsp; &nbsp; return strings.ReplaceAll(ms, p, "")}func main() {&nbsp; &nbsp; pattern := "helloworld."&nbsp; &nbsp; myString := "foo.bar.helloworld.qwerty.zxc"&nbsp; &nbsp; res := removeFromPattern(pattern, myString)&nbsp; &nbsp; fmt.Println(res)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go