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

How to remove string pattern and all the string behind that pattern?

例如:

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

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

1- 使用 _, after, _ = strings.Cut(ms, p),尝试 this:

func removeFromPattern(p, ms string) (after string) {
    _, after, _ = strings.Cut(ms, p) // before and after sep.
    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) {
    if i := Index(s, sep); i >= 0 {
        return s[:i], s[i+len(sep):], true
    }
    return s, "", false
}

2- 使用 strings.Index,尝试 this:

func removeFromPattern(p, ms string) string {
    i := strings.Index(ms, p)
    if i == -1 {
        return ""
    }
    return ms[i+len(p):]
}

3- 使用 strings.Split,尝试 this:

func removeFromPattern(p, ms string) string {
    a := strings.Split(ms, p)
    if len(a) != 2 {
        return ""
    }
    return a[1]
}

4- 使用 regexp,尝试 this

func removeFromPattern(p, ms string) string {
    a := regexp.MustCompile(p).FindStringSubmatch(ms)
    if len(a) < 2 {
        return ""
    }
    return a[1]
}

strings.Split够了

func main() {
    pattern := "helloworld."
    myString := "foo.bar.helloworld.qwerty.zxc"

    res := removeFromPattern(pattern, myString)
    fmt.Println(res)
}

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