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

报告相同问题?

悬赏问题

  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元