Go: Retrieve a string from between two characters

2019-07-21 10:58发布

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!

7条回答
一纸荒年 Trace。
2楼-- · 2019-07-21 11:27

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

查看更多
Bombasti
3楼-- · 2019-07-21 11:27
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
}
查看更多
ら.Afraid
4楼-- · 2019-07-21 11:36

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.

查看更多
Summer. ? 凉城
5楼-- · 2019-07-21 11:36

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.

查看更多
放荡不羁爱自由
6楼-- · 2019-07-21 11:36

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])
        }
    }
}
查看更多
地球回转人心会变
7楼-- · 2019-07-21 11:38

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!

查看更多
登录 后发表回答