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条)

报告相同问题?

悬赏问题

  • ¥15 给出完整的python代码并解释
  • ¥15 有人懂怎么做大模型的客服系统吗?卡住了卡住了
  • ¥20 firefly-rk3399上启动卡住了
  • ¥15 如何删除这个虚拟音频
  • ¥50 hyper默认的default switch
  • ¥15 网站打不开,提示502 Bad Gateway
  • ¥20 基于MATLAB的绝热压缩空气储能系统代码咨询
  • ¥15 R语言建立随机森林模型出现的问题
  • ¥15 关于#wpf#的问题:怎么更改LayoutGroup组件的标签页的字体颜色
  • ¥15 中级微观经济学,生产可能性边界问题