问题描述

我想使用正则表达式获取所有括号内的所有子字符串.

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"

 re.findall((?< = \()[^)] +(?= \))","foo(bar)foo(baz)golang")
re.findall("(?<=\()[^)]+(?=\))", "foo(bar)foo(baz)golang")

如何进行?

推荐答案

 go  regexp  regexp.FindAllStringSubmatch()
goregexpregexp.FindAllStringSubmatch()
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

 \(([[^)] +)\)
 \((
([[^)] +)).*?\)
([^)]+)).*?\)
 \))

这篇关于获取Golang正则表达式中括号内的所有子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!