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
From Regexp.FindStringSubmatch:
FindStringSubmatchreturns a slice of strings holding the text of the leftmost match of the regular expression in s and the matches
So:
12334' (leftmost match)12334'Another example:
re := regexp.MustCompile("a(x*)b(y|z)c")
fmt.Printf("%q\n", re.FindStringSubmatch("-axxxbyc-"))
That would print:
"axxxbyc""xxx" "y"If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With