Home > Enterprise >  How to remove string pattern and all the string behind that pattern?
How to remove string pattern and all the string behind that pattern?

Time:05-24

For Example :

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)
}

Wanted output :

qwerty.zxc.helloworld.asd

How do I get that wanted output, also how to remove the first pattern and all the strings behind that pattern from myString ?

CodePudding user response:

1- Using _, after, _ = strings.Cut(ms, p), try this:

func removeFromPattern(p, ms string) (after string) {
    _, after, _ = strings.Cut(ms, p) // before and after sep.
    return
}

Which uses 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- Using strings.Index, try this:

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

3- Using strings.Split, try this:

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

4- Using regexp, try this

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

CodePudding user response:

strings.Split is enough

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 ""
}

CodePudding user response:

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)
}
  • Related