Golang正则表达式在括号内得到值

时间:2016-10-07 03:36:18

标签: regex go

代码:

package main

import (
    "fmt"
    "regexp"
)

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

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

如何在括号内获取价值?

3 个答案:

答案 0 :(得分:8)

1-虽然使用正则表达式很简单(在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])
}

输出:

tag

2-但有时使用strings.Index足够快(在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)    
}

输出:

tag

3-这个简单的基准测试表明,使用正则表达式需要931毫秒,使用strings.Index需要43毫秒进行1000000次迭代。

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 ""
}

答案 1 :(得分:1)

我的问题通过这个正则表达式解决了

for (i in seq_along(numbers)) {
    if(numbers[i] %% 2 == 0) total[i] <- 1
}

答案 2 :(得分:0)

参考答案,我制作了代码版本。 链接:https://play.golang.org/p/b82iPZGU1gw

package main

import (
    "fmt"
    "strings"
)

func match(start, end, s string) string {
    i := strings.Index(s, start)
    if i >= 0 {
        j := strings.Index(s[i:], end)
        if j >= 0 {
            return s[i+len(start) : i+j]
        }
    }
    return ""
}

func main() {
    errText := `facebook: Error validating access token: Session has expired on Tuesday, 28-Jul-20 22:00:00 PDT. The current time is Wednesday, 29-Jul-20 17:55:22 PDT. (code: 190; error_subcode: 463, error_user_title: , error_user_msg: )`
    start := "code: "
    end := ";"
    r := match(start, end, errText)
    fmt.Println(r)
}