获取Golang正则表达式中括号内的所有子字符串

I want to get all the substrings inside all parentheses in go using Regex.

As an example for the string "foo(bar)foo(baz)golang", i want "bar" and "baz"

in python i can do re.findall("(?<=\()[^)]+(?=\))", "foo(bar)foo(baz)golang")

How to do it in go?

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])
    }
}

outputs:

bar
baz

The Regex \(([^)]+)\):

  • \( matches literal (

  • ([^)]+) matches substring upto next ) and put the match in a captured group, here you can use non-greeedy match .*?\) too

  • \) matches literal )


Go playground demo

Try this:

\((.*?)\)

Explanation

Code Sample:

package main

import (
    "regexp"
    "fmt"
)

func main() {
    var re = regexp.MustCompile(`\((.*?)\)`)
    var str = `foo(bar)foo(baz)golang`

    mt:= re.FindAllStringSubmatch(str, -1)

    for _, i := range mt {
        fmt.Println(i[1])
    }
}

Run the go code here