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

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"