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

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

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

{city}, {state} {zip}

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

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

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dssqq82402
    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.

    点赞 评论

相关推荐