Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 955
T145 Avatar asked Nov 13 '14 19:11

T145


3 Answers

I improved the Jan Kardaš`s answer. now you can find string with more than 1 character at the start and end.

func GetStringInBetweenTwoString(str string, startS string, endS string) (result string,found bool) {
    s := strings.Index(str, startS)
    if s == -1 {
        return result,false
    }
    newS := str[s+len(startS):]
    e := strings.Index(newS, endS)
    if e == -1 {
        return result,false
    }
    result = newS[:e]
    return result,true
}
like image 92
ttrasn Avatar answered Sep 30 '22 05:09

ttrasn


Here is my answer using regex. Not sure why no one suggested this safest approach

package main

import (
    "fmt"
        "regexp"
)

func main() {
    content := "<h1>Hello World!</h1>"
    re := regexp.MustCompile(`<h1>(.*)</h1>`)
    match := re.FindStringSubmatch(content)
    if len(match) > 1 {
        fmt.Println("match found -", match[1])
    } else {
        fmt.Println("match not found")
    }
    
}

Playground - https://play.golang.org/p/Yc61x1cbZOJ

like image 39
dganesh2002 Avatar answered Sep 30 '22 03:09

dganesh2002


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

like image 33
DiBa Avatar answered Sep 30 '22 05:09

DiBa