Search code examples
stringgosubstring

Go: Retrieve a string from between two characters or other strings


Let's say for example that I have one string, like this:

<h1>Hello World!</h1>

What Go code would be able to extract Hello World! from that string? I'm still relatively new to Go. Any help is greatly appreciated!


Solution

  • There are lots of ways to split strings in all programming languages.

    Since I don't know what you are especially asking for I provide a sample way to get the output you want from your sample.

    package main
    
    import "strings"
    import "fmt"
    
    func main() {
        initial := "<h1>Hello World!</h1>"
    
        out := strings.TrimLeft(strings.TrimRight(initial,"</h1>"),"<h1>")
        fmt.Println(out)
    }
    

    In the above code you trim <h1> from the left of the string and </h1> from the right.

    As I said there are hundreds of ways to split specific strings and this is only a sample to get you started.

    Hope it helps, Good luck with Golang :)

    DB