3

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?

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Note that this could panic if the second call to index returns -1 because "/" was not found. Then i > j in s[i:j] which causes panic.
3

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..."]

Comments

1

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.

Comments

-1

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

1 Comment

Benchmarks in Go are easy so it's not opinion if it will be "more faster". Using a regexp for such a simple task is ~17× slower and does three vs zero allocations (and that's with precompiling the regexp only once in a global).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.