问题描述
我试图返回一个数组或切片,其中包含针对字符串的特定正则表达式的所有匹配项.字符串是:
I am trying to return an array, or slice, with all the matches for a specific regex expression against a string. The string is:
{city}, {state} {zip}
我想返回一个包含花括号之间所有字符串匹配项的数组.我尝试使用 regexp 包来完成此操作,但无法弄清楚如何返回我要查找的内容.这是我当前的代码:
I want to return an array with all the matches of strings between curly braces. I have tried using the regexp package to accomplish this but cannot figure out how to return what I am looking for. This is my current code:
r := regexp.MustCompile("/({[^}]*})/")
matches := r.FindAllString("{city}, {state} {zip}", -1)
但是,无论我尝试什么,它每次返回的内容都是空的.
But, all it returns is an empty slice every time no matter what I try.
推荐答案
{}{city}{state}{zip}
{}{city}{state}{zip}
FindAllString
FindAllString
r := regexp.MustCompile(`{[^{}]*}`)
matches := r.FindAllString("{city}, {state} {zip}", -1)
FindAllStringSubmatch{([^{}]*)}
FindAllStringSubmatch{([^{}]*)}
r := regexp.MustCompile(`{([^{}]*)}`)
matches := r.FindAllStringSubmatch("{city}, {state} {zip}", -1)
for _, v := range matches {
fmt.Println(v[1])
}
正则表达式详细信息
{{([^{}]*){}*[^...][^]}}
{{([^{}]*)*{}[^...][^]}}
这篇关于查找与正则表达式golang匹配的所有字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!