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

后端 未结 7 1730
有刺的猬
有刺的猬 2021-01-05 14:47

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

Hello World!

What Go code would be able to extract Hel

7条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-05 15:26

    If the string looks like whatever;START;extract;END;whatever you can use this which will get the string in between:

    // GetStringInBetween Returns empty string if no start string found
    func GetStringInBetween(str string, start string, end string) (result string) {
        s := strings.Index(str, start)
        if s == -1 {
            return
        }
        s += len(start)
        e := strings.Index(str[s:], end)
        if e == -1 {
            return
        }
        return str[s:e]
    }
    

    What happens here is it will find first index of START, adds length of START string and returns all that exists from there until first index of END.

提交回复
热议问题