我试图返回一个数组或片,其中包含针对字符串的特定 regex 表达式的所有匹配项。字符串是:
{city}, {state} {zip}
我想返回一个数组,其中包含大括号之间的所有字符串匹配项。我已经尝试使用 regexp 包来实现这一点,但是不知道如何返回我正在寻找的内容。这是我当前的代码:
r := regexp.MustCompile("/({[^}]*})/")
matches := r.FindAllString("{city}, {state} {zip}", -1)
但是,无论我尝试什么,它每次返回的都是一片空白。
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.