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

huangapple go评论68阅读模式
英文:

Get all substrings inside parentheses in Golang regexp

问题

我想使用正则表达式在Go语言中获取所有括号内的子字符串。

以字符串"foo(bar)foo(baz)golang"为例,我想要获取"bar"和"baz"。

在Python中,我可以使用re.findall("(?<=\()[^)]+(?=\))", "foo(bar)foo(baz)golang")来实现。

在Go语言中该如何实现呢?

英文:

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(&quot;(?&lt;=\()[^)]+(?=\))&quot;, &quot;foo(bar)foo(baz)golang&quot;)

How to do it in go?

答案1

得分: 5

goregexp包不支持零宽断言。你可以利用regexp.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

正则表达式\(([^)]+)\)

  • \( 匹配字面上的 (

  • ([^)]+) 匹配到下一个 ) 之前的子字符串,并将匹配结果放入一个捕获分组中,你也可以使用非贪婪匹配 .*?\)

  • \) 匹配字面上的 )


Go playground演示

英文:

go's regexp package does not support zero width lookarounds. You can leverage captured grouping with the regexp.FindAllStringSubmatch() function:

package main

import (
	&quot;regexp&quot;
	&quot;fmt&quot;
)

func main() {
	str := &quot;foo(bar)foo(baz)golang&quot;
	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

答案2

得分: 0

尝试这个:

\((.*?)\)

解释

代码示例:

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

在这里运行Go代码

英文:

Try this:

\((.*?)\)

Explanation

Code Sample:

package main

import (
    &quot;regexp&quot;
    &quot;fmt&quot;
)

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

huangapple
  • 本文由 发表于 2016年11月14日 18:16:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/40586313.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定