dongyanju0945 2019-04-01 08:19
浏览 101
已采纳

正则表达式在字符串中找到很多单词

I want to get all work in string - that are between the pair of {word}

Example:

payment://pay?id={appid}&transtoken={transtoken}

Result expect:

["appid", "transtoken"]

With regex partern: {\w+}, I only can get [{appid}, {transtoken}].

Please help me with the problem.

  • 写回答

2条回答 默认 最新

  • dspvin19712 2019-04-01 08:28
    关注

    You may use the following pattern with FindAllStringSubmatch:

    {(\w+)}
    

    See the Go regexp documentation:

    FindAllStringSubmatch is the 'All' version of FindStringSubmatch; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.

    and

    FindStringSubmatch returns a slice of strings holding the text of the leftmost match of the regular expression in s and the matches, if any, of its subexpressions, as defined by the 'Submatch' description in the package comment. A return value of nil indicates no match.

    See the Go demo:

    package main
    
    import (
        "fmt"
        "regexp"
    )
    
    func main() {
        s := `payment://pay?id={appid}&transtoken={transtoken}`
        rex := regexp.MustCompile(`{(\w+)}`)
        results := rex.FindAllStringSubmatch(s,-1)
        for _, value := range results  {
            fmt.Printf("%q
    ", value[1])
        }
    }
    

    Output:

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

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料