在Golang中提取部分字符串?

Joh*_*ith 4 go

我正在学习Golang,所以我可以重写一些shell脚本.

我的URL看起来像这样:

https://example-1.example.com/a/c482dfad3573acff324c/list.txt?parm1=value,parm2=value,parm3=https://example.com/a?parm1=value,parm2=value
Run Code Online (Sandbox Code Playgroud)

我想提取以下部分:

https://example-1.example.com/a/c482dfad3573acff324c/list.txt
Run Code Online (Sandbox Code Playgroud)

在shell脚本中我会做这样的事情:

echo "$myString" | grep -o 'http://.*.txt'
Run Code Online (Sandbox Code Playgroud)

只使用标准库,在Golang中做同样事情的最佳方法是什么?

Cer*_*món 12

有几个选择:

// match regexp as in question
pat := regexp.MustCompile(`https?://.*\.txt`)
s := pat.FindString(myString)

// everything before the query 
s := strings.Split(myString, "?")[0] string

// same as previous, but avoids []string allocation
s := myString
if i := strings.IndexByte(s, '?'); i >= 0 {
    s = s[:i]
}

// parse and clear query string
u, err := url.Parse(myString)
u.RawQuery = ""
s := u.String()
Run Code Online (Sandbox Code Playgroud)

最后一个选项是最好的,因为它将处理所有可能的极端情况.

try it on the playground