Products
GG网络技术分享 2025-03-18 16:15 1
Code:
package mainimport (
\"fmt\"
\"regexp\"
)
func main() {
r := regexp.MustCompile(`((.*))`)
s := `(tag)SomeText`
res := r.FindStringSubmatch(s)
fmt.Println(res[1])
}
How to Get Value inside parentheses?
图片转代码服务由CSDN问答提供
感谢您的意见,我们尽快改进~
功能建议代码:</ p>
包main import(\\ n“ fmt”
“ regexp”
)
func main(){
r:= regexp.MustCompile(`((。*))`)
s:=`(tag)SomeText`
\\ n res:= r.FindStringSubmatch(s)
fmt.Println(res [1])
}
</ code> </ pre>
如何在括号内获取值?</ p>
</ div>
网友观点:
1- While it is simple using regex (try it on The Go Playground):
package mainimport (
\\\"fmt\\\"
\\\"regexp\\\"
)
var rgx = regexp.MustCompile(`\\((.*?)\\)`)
func main() {
s := `(tag)SomeText`
rs := rgx.FindStringSubmatch(s)
fmt.Println(rs[1])
}
output:
tag
2- but sometimes using strings.Index
is fast enough (try it on The Go Playground):
package mainimport (
\\\"fmt\\\"
\\\"strings\\\"
)
func match(s string) string {
i := strings.Index(s, \\\"(\\\")
if i >= 0 {
j := strings.Index(s[i:], \\\")\\\")
if j >= 0 {
return s[i+1 : j-i]
}
}
return \\\"\\\"
}
func main() {
s := `(tag)SomeText`
r := match(s)
fmt.Println(r)
}
output:
tag
3- This simple benchmark shows using regex takes 931ms and using strings.Index
takes 43ms for 1000000 iterations.
package mainimport (
\\\"fmt\\\"
\\\"regexp\\\"
\\\"strings\\\"
\\\"time\\\"
)
var rgx = regexp.MustCompile(`\\((.*?)\\)`)
const n = 1000000
func main() {
var rs []string
var r string
s := `(tag)SomeText`
t := time.Now()
for i := 0; i < n; i++ {
rs = rgx.FindStringSubmatch(s)
}
fmt.Println(time.Since(t))
fmt.Println(rs[1]) // [(tag) tag]
t = time.Now()
for i := 0; i < n; i++ {
r = match(s)
}
fmt.Println(time.Since(t))
fmt.Println(r)
}
func match(s string) string {
i := strings.Index(s, \\\"(\\\")
if i >= 0 {
j := strings.Index(s[i:], \\\")\\\")
if j >= 0 {
return s[i+1 : j-i]
}
}
return \\\"\\\"
}
I got My problem solved by this regex
r := regexp.MustCompile(`\\((.*?)\\)`)
在python中,如何用正则表达式提取多层括号中最外层括号包含的内容呢?
不规则嵌套结构的分析
最好还是用栈
如果已经确定嵌套的结构
才可以考虑使用正则
先用贪婪取出整体的数据
然后对数据规划出相似的结构
第一个很简单就不用说了
第二个可以写成这样
Demand feedback