Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove string pattern and all the string behind?

For example :

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

func removeFromPattern(p, ms string) {
   // I confused here (in efficient way)
}

res := removeFromPattern(pattern, myString)

I want to get res = "qwerty.zxc"

how do I get qwerty.zxc only, and remove foo.bar.helloworld. from myString using pattern ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading