dongyunwei8596 2016-08-23 13:41 采纳率: 100%
浏览 1041
已采纳

如何查找与正则表达式golang匹配的所有字符串?

我试图返回一个数组或片,其中包含针对字符串的特定 regex 表达式的所有匹配项。字符串是:

{city}, {state} {zip}

我想返回一个数组,其中包含大括号之间的所有字符串匹配项。我已经尝试使用 regexp 包来实现这一点,但是不知道如何返回我正在寻找的内容。这是我当前的代码:

r := regexp.MustCompile("/({[^}]*})/")
matches := r.FindAllString("{city}, {state} {zip}", -1)

但是,无论我尝试什么,它每次返回的都是一片空白。

  • 写回答

1条回答 默认 最新

  • dssqq82402 2016-08-23 13:45
    关注

    First, you do not need the regex delimiters. Second, it is a good idea to use raw string literals to define a regex pattern where you need to use only 1 backslash to escape regex metacharacters. Third, the capturing group is only necessary if you need to get the values without { and }, thus, you may remove it to get {city}, {state} and {zip}.

    You may use FindAllString to get all matches:

    r := regexp.MustCompile(`{[^}]*}`)
    matches := r.FindAllString("{city}, {state} {zip}", -1)
    

    See the Go demo.

    To only get the parts between curly braces use FindAllStringSubmatch with a pattern that contains capturing parentheses, {([^}]*)}:

    r := regexp.MustCompile(`{([^}]*)}`)
    matches := r.FindAllStringSubmatch("{city}, {state} {zip}", -1)
    for _, v := range matches {
        fmt.Println(v[1])
    }
    

    See this Go demo.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?