Conor
Conor

Reputation: 781

Splitting string before and after certain parameters in Go

My string splitting skills are really poor using Go. I don't know why but I just can't wrap my head around this one and I've tried different ways to do what I need but I always get the wrong output.

I have this string:

https://docs.google.com/spreadsheets/d/1k2RNDSh6K7jH3fezjjfgVrHqVstBF569al4F28hqAM/edit#gid=0

I need to get a key from this URL that is found after '/d/' up until the next '/'.

So the key in this case would be:

1k2RNDSh6K7jH3fezjjfgVrHqVstBF569al4F28hqAM

How would I go about doing this?

Upvotes: 3

Views: 891

Answers (4)

VonC
VonC

Reputation: 1323953

Go 1.18 will come with func Cut(s, sep string) (before, after string, found bool), from issue 46336 and CL 351710

s := "https://docs.google.com/spreadsheets/d/1k2RNDSh6K7jH3fezjjfgVrHqVstBF569al4F28hqAM/edit#gid=0"
_,after,found := strings.Cut(s, "/d/")
if found {
    // after is 1k2RNDSh6K7jH3fezjjfgVrHqVstBF569al4F28hqAM/edit#gid=0"
    before, _, _ := strings.Cut(after, "/")
    // before is 1k2RNDSh6K7jH3fezjjfgVrHqVstBF569al4F28hqAM
    fmt.Println(before)
}

No more Index() and SplitN().
A lot of places in stand lib will benefit from strings.Cut(): CL 351711.

Upvotes: 1

Kishore
Kishore

Reputation: 9656

There are many alternatives to do this, here is the one which I used regular expression.

s := "https://docs.google.com/spreadsheets/d/1k2RNDSh6K7jH3fezjjfgVrHqVstBF569al4F28hqAM/edit#gid=0"
re := regexp.MustCompile("/d/(.*)?/").FindAllStringSubmatch(s, -1)
fmt.Println("found the pattern :", re[0][1])

https://play.golang.org/p/l6B4AE-4to

Upvotes: -1

RCZiegler
RCZiegler

Reputation: 41

I have never used "go" but it looks like you could utilize

func Split(s, set string) []string

Example:

fmt.Printf("%q\n", strings.Split("https://docs.google.com/spreadsheets/d/1234567890/edit#gid...", "/"))

would return the array

["https:" "" "docs.google.com" "spreadsheets" "d" "1234567890" "edit#gid..."]

Upvotes: 3

Ainar-G
Ainar-G

Reputation: 36199

strings.Index can help you with this:

s := "https://docs.google.com/spreadsheets/d/1k2RNDSh6K7jH3fezjjfgVrHqVstBF569al4F28hqAM/edit#gid=0"
i := strings.Index(s, "/d/") + len("/d/")
j := strings.Index(s[i:], "/") + i
fmt.Println(s[i:j]) // Prints "1k2RNDSh6K7jH3fezjjfgVrHqVstBF569al4F28hqAM"

Playground: http://play.golang.org/p/Mqnnc_tNFk.

Upvotes: 5

Related Questions