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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵