在Go语言中,获取URL样式字符串中的第一个目录。

huangapple go评论78阅读模式
英文:

Retrieve first directory in URL-like string in Go

问题

我正在尝试获取类似URL的字符串中的第一个目录,例如"/blog/:year/:daynum/:postname"。我以为将其拆分,然后获取第一个目录会很简单。但是,即使它不是一个切片,它返回了方括号括住的字符串。我该如何获取第一个目录?(我保证字符串以"/"开头,后跟有效的目录指定,并且包含使用这些永久链接属性的前导目录和字符串)。

解析出第一个目录的最佳方法是什么?

package main
import (
	"fmt"
	"strings"
)
// 获取URL-like字符串中的第一个目录
func firstDir(permalink string) string {
	split := strings.Split(permalink, "/")
	return string(fmt.Sprint((split[0:2])))
}
func main() {
	permalink := "/blog/:year/:daynum/:postname"
	dir := firstDir(permalink)
	fmt.Printf("leading dir is: %s.", dir)
	// 输出的结果不是"blog",而是"[ blog]"。
}
英文:

I am trying to obtain the first directory in an URL-like string like this: "/blog/:year/:daynum/:postname". I thought splitting it, then retrieving the first directory, would be this simple. But it returns square brackets surrounding the string even though it's not a slice. How can I get that first directory? (I am guaranteed that the string starts with a "/" followed by a valid directory designation and that contains both a leading directory and a string using those permalink properties).

What's the best way to parse out that first directory?

package main
import (
	"fmt"
	"strings"
)
// Retrieve the first directory in the URL-like
// string passed in
func firstDir(permalink string) string {
	split := strings.Split(permalink, "/")
	return string(fmt.Sprint((split[0:2])))
}
func main() {
	permalink := "/blog/:year/:daynum/:postname"
	dir := firstDir(permalink)
	fmt.Printf("leading dir is: %s.", dir)
	// Prints NOT "blog" but "[ blog]".
}

答案1

得分: 2

由于您提到:“(我保证字符串以“/”开头,后跟有效的目录指定,并且包含使用这些永久链接属性的前导目录和字符串)”

那么只需使用split[1]来获取根目录。

package main

import (
	"fmt"
	"os"
	"strings"
)

func firstDir(permalink string) string {
	split := strings.Split(permalink, string(os.PathSeparator))
	return split[1]
}

func main() {
	permalink := "/blog/:year/:daynum/:postname"
	dir := firstDir(permalink)
	fmt.Printf("leading dir is: %s.", dir)
	// 输出 "blog"。
}

您可以在此链接中查看代码的运行结果:https://go.dev/play/p/hCHnrDIsWYE

英文:

Since you said:"(I am guaranteed that the string starts with a "/" followed by a valid directory designation and that contains both a leading directory and a string using those permalink properties)"

Then simply use split[1] to get the root directory.

package main

import (
	"fmt"
	"os"
	"strings"
)

func firstDir(permalink string) string {
	split := strings.Split(permalink, string(os.PathSeparator))
	return split[1]
}
func main() {
	permalink := "/blog/:year/:daynum/:postname"
	dir := firstDir(permalink)
	fmt.Printf("leading dir is: %s.", dir)
	// Prints "blog".
}

https://go.dev/play/p/hCHnrDIsWYE

huangapple
  • 本文由 发表于 2021年12月14日 08:42:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/70342539.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定