代码之家  ›  专栏  ›  技术社区  ›  Anh Vinh Huỳnh

正则表达式在字符串中查找多个单词

  •  0
  • Anh Vinh Huỳnh  · 技术社区  · 7 年前

    我想把所有的工作都放在绳子上-那是一对 {word}

    例子:

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

    预期结果:

    ["appid", "transtoken"]
    

    与regex partern: {\w+} [{appid}, {transtoken}] .

    请帮我解决这个问题。

    2 回复  |  直到 7 年前
        1
  •  3
  •   Wiktor Stribiżew    7 年前

    你可以用下面的图案 FindAllStringSubmatch :

    {(\w+)}
    

    请参阅Go regexp文档:

    FindAllStringSubmatch 是的“全部”版本 FindStringSubmatch

    返回包含中正则表达式最左侧匹配的文本的字符串片段 s ,由包注释中的“Submatch”说明定义。返回值nil表示不匹配。

    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\n", value[1])
        }
    }
    

    输出:

    "appid"
    "transtoken"