drau67562 2016-07-27 23:08
浏览 618
已采纳

在Golang中提取部分字符串?

I'm learning Golang so I can rewrite some of my shell scripts.

I have URL's that look like this:

https://example-1.example.com/a/c482dfad3573acff324c/list.txt?parm1=value,parm2=value,parm3=https://example.com/a?parm1=value,parm2=value

I want to extract the following part:

https://example-1.example.com/a/c482dfad3573acff324c/list.txt

In a shell script I would do something like this:

echo "$myString" | grep -o 'http://.*.txt'

What is the best way to do the same thing in Golang, only by using the standard library?

  • 写回答

3条回答 默认 最新

  • doudou348131346 2016-07-27 23:19
    关注

    There are a few options:

    // 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()
    

    The last option is the best because it will handle all possible corner cases.

    <kbd>try it on the playground</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?