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

后端 未结 7 1723
有刺的猬
有刺的猬 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:36

    func Split(str, before, after string) string {
        a := strings.SplitAfterN(str, before, 2)
        b := strings.SplitAfterN(a[len(a)-1], after, 2)
        if 1 == len(b) {
            return b[0]
        }
        return b[0][0:len(b[0])-len(after)]
    }
    

    the first call of SplitAfterN will split the original string into array of 2 parts divided by the first found after string, or it will produce array containing 1 part equal to the original string.

    second call of SplitAfterN uses a[len(a)-1] as input, as it is "the last item of array a". so either string after after or the original string str. the input will be split into array of 2 parts divided by the first found before string, or it will produce array containing 1 part equal to the input.

    if after was not found than we can simply return b[0] as it is equal to a[len(a)-1]

    if after is found, it will be included at the end of b[0] string, therefore you have to trim it via b[0][0:len(b[0])-len(after)]

    all strings are case sensitive

提交回复
热议问题