获取Golang正则表达式中括号内的所有子字符串 [英] Get all substrings inside parentheses in Golang regexp
问题描述
我想使用正则表达式获取所有括号内的所有子字符串.
I want to get all the substrings inside all parentheses in go using Regex.
作为字符串"foo(bar)foo(baz)golang"的示例,我想要"bar"和"baz"
As an example for the string "foo(bar)foo(baz)golang", i want "bar" and "baz"
在python中,我可以做 re.findall((?< = \()[^)] +(?= \))","foo(bar)foo(baz)golang")
in python i can do re.findall("(?<=\()[^)]+(?=\))", "foo(bar)foo(baz)golang")
如何进行?
推荐答案
go
的 regexp
包不支持零宽度环顾.您可以使用 regexp.FindAllStringSubmatch()
函数利用捕获的分组:
go
's regexp
package does not support zero width lookarounds. You can leverage captured grouping with the regexp.FindAllStringSubmatch()
function:
package main
import (
"regexp"
"fmt"
)
func main() {
str := "foo(bar)foo(baz)golang"
rex := regexp.MustCompile(`\(([^)]+)\)`)
out := rex.FindAllStringSubmatch(str, -1)
for _, i := range out {
fmt.Println(i[1])
}
}
输出:
bar
baz
正则表达式 \(([[^)] +)\)
:
-
\(
匹配文字(
([[^)] +)
匹配子字符串直到下一个)
并将匹配项放入捕获的组中,在这里您可以使用非贪婪匹配.*?\)
([^)]+)
matches substring upto next )
and put the match in a captured group, here you can use non-greeedy match .*?\)
too
\)
匹配文字)
这篇关于获取Golang正则表达式中括号内的所有子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!