Go regexp FindAllStringSubmatch

huangapple go评论85阅读模式
英文:

Go regexp FindAllStringSubmatch

问题

这是我的Go代码片段,可以在这里找到: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))

}

我期望的结果是[[2d3h 3h] [3h5d 5d]],但实际结果是[[2d3h 3h]]。你能解释一下为什么吗?提前谢谢。

英文:

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

得分: 4

原因是你无法获得重叠的结果。对于支持前瞻的正则表达式引擎,你可以使用技巧:(?=([0-9]+[dh]){2}),但是Go语言不支持它。

如果你想获取所有的结果,我建议你使用FindAllStringIndex()([0-9]+[dh]),然后确定所有连续的子字符串和偏移量。

英文:

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.

huangapple
  • 本文由 发表于 2013年12月5日 17:01:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/20395562.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定