英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论