Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FindStringSubmatch returns matched group twice

Tags:

go

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\n", 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

like image 355
linuxfan Avatar asked Oct 31 '25 04:10

linuxfan


1 Answers

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\n", re.FindStringSubmatch("-axxxbyc-"))

That would print:

  • the leftmost match: "axxxbyc"
  • the two captured groups: "xxx" "y"
like image 94
VonC Avatar answered Nov 03 '25 03:11

VonC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!