Go regexp FindAllStringSubmatch

Viewed 1010

here is my snippet of code in Go which can be found here http://play.golang.org/p/L1AcgHf3E4.

package main

import (
    "fmt"
    "regexp"
)

func main() {
    reg := regexp.MustCompile("([0-9]+[dh]){2}")
    str := "2d3h5d"

    fmt.Println(reg.FindAllStringSubmatch(str, -1))

}

I'd expect the result to be [[2d3h 3h] [3h5d 5d]], but it turned out to be [[2d3h 3h]]. Can you explain why? Thanks in advance.

1 Answers

the reason is that you can not obtain overlapping results. With regex engines that support lookahead you can use the trick: (?=([0-9]+[dh]){2}) but go language does not support it.

If you want to obtain all results, I suggest you to use FindAllStringIndex() with ([0-9]+[dh]) and then determine all contiguous substrings with the offset.

Related