Products
GG网络技术分享 2025-03-18 16:15 6
我试图返回一个数组或片,其中包含针对字符串的特定 regex 表达式的所有匹配项。字符串是:
{city}, {state} {zip}
我想返回一个数组,其中包含大括号之间的所有字符串匹配项。我已经尝试使用 regexp 包来实现这一点,但是不知道如何返回我正在寻找的内容。这是我当前的代码:
r := regexp.MustCompile(\"/({[^}]*})/\")matches := r.FindAllString(\"{city}, {state} {zip}\", -1)
但是,无论我尝试什么,它每次返回的都是一片空白。
图片转代码服务由CSDN问答提供
感谢您的意见,我们尽快改进~
功能建议我试图返回一个数组或切片,其中包含针对字符串的特定正则表达式的所有匹配项。 字符串为:</ p>
{city},{state} {zip} </ code> </ pre>
我想返回一个 大括号之间的所有字符串匹配项组成的数组。 我尝试使用 regexp 包来完成此操作,但无法弄清楚如何返回我要查找的内容。 这是我当前的代码:</ p>
r:= regexp.MustCompile(“ /({{^^] *})/”)matches:= r.FindAllString(“ {city},{state} {zip}”,-1)
</ code> </ pre>
但是,无论我尝试什么,每次返回的结果都是空片。< / p>
</ div>
网友观点:
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.
正则表达式如何匹配“字符串中的字符串”?
替换就可以,“\\\\””替换成“\\””,“\\\\\\”替换成“\\\\”。如果不转义那就是:“\\””替换成“”””,“\\\\”替换成“\\”
Demand feedback