Golang正则表达式在括号内获取值

Code:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    r := regexp.MustCompile(`((.*))`)
    s := `(tag)SomeText`

    res := r.FindStringSubmatch(s)
    fmt.Println(res[1])
}

How to Get Value inside parentheses?

1- While it is simple using regex (try it on The Go Playground):

package main

import (
    "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 main

import (
    "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 main

import (
    "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(`\((.*?)\)`)