找到所有与Regex golang匹配的字符串

问题描述 投票:4回答:1

我试图返回一个数组或切片,与字符串的特定正则表达式的所有匹配。字符串是:

{city}, {state} {zip}

我想返回一个数组,其中包含花括号之间的所有字符串匹配。我已经尝试使用regexp包来完成这个,但无法弄清楚如何返回我正在寻找的东西。这是我目前的代码:

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

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

regex go
1个回答
5
投票

首先,您不需要正则表达式分隔符。其次,使用原始字符串文字定义正则表达式模式是个好主意,您只需要使用1个反斜杠来转义正则表达式元字符。第三,只有你需要获得没有{}的值时才需要捕获组,因此,你可以删除它以获得{city}{state}{zip}

您可以使用FindAllString获取所有比赛:

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

Go demo

要仅获取花括号之间的部分,请使用带有捕获括号的模式的FindAllStringSubmatch{([^}]*)}

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

this Go demo

© www.soinside.com 2019 - 2024. All rights reserved.