duanci8209
2016-10-07 03:36
浏览 1.4k
已采纳

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?

图片转代码服务由CSDN问答提供 功能建议

代码:

 包main 
 
import(\  n“ fmt” 
“ regexp” 
)
 
func main(){
r:= regexp.MustCompile(`((。*))`)
s:=`(tag)SomeText` 
 \  n res:= r.FindStringSubmatch(s)
 fmt.Println(res [1])
} 
   
 
 

如何在括号内获取值?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongxieli3839 2016-10-07 08:44
    已采纳

    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 ""
    }
    
    打赏 评论
  • douyu1656 2016-10-07 03:55

    I got My problem solved by this regex

    r := regexp.MustCompile(`\((.*?)\)`)
    
    打赏 评论

相关推荐 更多相似问题