dragon8899 2014-11-14 18:17
浏览 50
已采纳

FindStringSubmatch返回匹配的组两次

Perhaps I'm missing something very basic about the go's regexp.FindStringSubmatch(). I want to capture the group with all digits that follows the string "Serial Number: " but get unexpected output. My code is as below:

package main
import "fmt"
import "regexp"

func main() {

    x := "Serial Number: 12334"
    r := regexp.MustCompile(`(\d+)`)
    res := r.FindStringSubmatch(x)

    for i,val := range res {
        fmt.Printf("entry %d:%s
", i,val)
    }
}

The output is:

entry 0:12334
entry 1:12334

I'm more familiar with python's grouping that seems pretty straight-forward:

>>> re.search('(\d+)', "Serial Number: 12344").groups()[0]
'12344'

How can I get the grouping to work in go? thanks

  • 写回答

1条回答 默认 最新

  • dos71253 2014-11-14 18:19
    关注

    From Regexp.FindStringSubmatch:

    FindStringSubmatch returns a slice of strings holding the text of the leftmost match of the regular expression in s and the matches

    So:

    • the first entry is what has been matched: '12334' (leftmost match)
    • the second entry is the one captured group: '12334'

    Another example:

    re := regexp.MustCompile("a(x*)b(y|z)c")
    fmt.Printf("%q
    ", re.FindStringSubmatch("-axxxbyc-"))
    

    That would print:

    • the leftmost match: "axxxbyc"
    • the two captured groups: "xxx" "y"
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 写uniapp时遇到的问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流