Go to findAllStringSubmatch regex

here is my Go code snippet that 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 expect that the result will be [[2d3h 3h] [3h5d 5d]], but it turned out [[2d3h 3h]]. Can you explain why? Thanks in advance.

+4
source share
1 answer

the reason is that you cannot get overlapping results. With regular expressions that support lookahead, you can use the: trick (?=([0-9]+[dh]){2}), but the language does not support it.

If you want to get all the results, I suggest you use FindAllStringIndex()c ([0-9]+[dh]), and then define all continuous substrings with an offset.

+3

All Articles