转到:从两个字符或其他字符串之间检索字符串

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!

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

Read up on the strings package. Have a look into the SplitAfter function which can do something like this:

var sample = "[this][is my][string]"
t := strings.SplitAfter(sample, "[")

That should produce a slice something like: "[", "this][", "is my][", "string]". Using further functions for Trimming you should get your solution. Best of luck.

In the strings pkg you can use the Replacer to great affect.

r := strings.NewReplacer("<h1>", "", "</h1>", "")
fmt.Println(r.Replace("<h1>Hello World!</h1>"))

Go play!

If the string looks like whatever;START;extract;END;whatever you can use this:

// 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, end)
    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.

func findInString(str, start, end string) ([]byte, error) {
    var match []byte
    index := strings.Index(str, start)

    if index == -1 {
        return match, errors.New("Not found")
    }

    index += len(start)

    for {
        char := str[index]

        if strings.HasPrefix(str[index:index+len(match)], end) {
            break
        }

        match = append(match, char)
        index++
    }

    return match, nil
}
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

Just had a similar problem, only that I did not know if my input string s contained any or even multiple pairs of the START or STOP characters! So my general solution is:

s := "\x02this is a test\x03-\x02another test\x03"
start, end := "\x02", "\x03" // just replace these with whatever you like...
sSplits := strings.Split(s, start)
result := []string{}

if len(sSplits) > 1 { // n splits = 1 means start char not found!
    for _, subStr := range sSplits { // check each substring for end
        ixEnd := strings.Index(subStr, end)
        if ixEnd != -1 {
            result = append(result, subStr[:ixEnd])
        }
    }
}