英文:
Using golangs regex for parsing sports score
问题
我正在使用golang的正则表达式来解析体育比分,但是找不到原因,为什么它只解析了第一个和最后一个比分部分,而不是所有的部分。
package main
import (
"fmt"
"regexp"
)
func main() {
var FirstQuarterBasketballRegexp = regexp.MustCompile(`^(\d+:\d+)\s\((?:(\d+:\d+)(?:,\s)?)+\)$`)
fmt.Printf("%q\n", FirstQuarterBasketballRegexp.FindAllStringSubmatch("102:72 (28:17, 27:15, 24:14, 23:26)", -1))
}
它打印了一个字符串
[["102:72 (28:17, 27:15, 24:14, 23:26)" "102:72" "23:26"]]
为什么它只包含了切片中的3个元素?
英文:
I'm trying use golang regex for parsing sports score, but can't found a reason, why it doesn't parse all scores parts, but only the first and the last.
package main
import (
"fmt"
"regexp"
)
func main() {
var FirstQuarterBasketballRegexp = regexp.MustCompile(`^(\d+:\d+)\s\((?:(\d+:\d+)(?:,\s)?)+\)$`)
fmt.Printf("%q\n", FirstQuarterBasketballRegexp.FindAllStringSubmatch("102:72 (28:17, 27:15, 24:14, 23:26)", -1))
}
It prints a string
[["102:72 (28:17, 27:15, 24:14, 23:26)" "102:72" "23:26"]]
Why it contains only 3 elem in a slice?
答案1
得分: 3
它返回3个元素,因为有第0个组(整个字符串)和2个捕获组:
- [0-6]
102:72
- [29-34]
23:26
现在,你应该考虑你需要什么,只使用你需要的部分。
也许,你正在寻找(\d+:\d+)
,它将返回:
102:72
28:17
27:15
24:14
23:26
尝试这段代码(示例程序在这里):
func main() {
var FirstQuarterBasketballRegexp = regexp.MustCompile(`\d+:\d+`)
fmt.Printf("%q\n", FirstQuarterBasketballRegexp.FindAllStringSubmatch("102:72 (28:17, 27:15, 24:14, 23:26)", -1))
}
输出:
[["102:72"] ["28:17"] ["27:15"] ["24:14"] ["23:26"]]
英文:
It returns 3 elements, as there is 0th group (the whole string), and 2 capturing groups:
1. [0-6] `102:72`
2. [29-34] `23:26`
Now, you should think about what you need, and only use what you need.
Perhaps, you are looking for (\d+:\d+)
that will return
102:72
28:17
27:15
24:14
23:26
Try this code (sample program is available here):
func main() {
var FirstQuarterBasketballRegexp = regexp.MustCompile(`\d+:\d+`)
fmt.Printf("%q\n", FirstQuarterBasketballRegexp.FindAllStringSubmatch("102:72 (28:17, 27:15, 24:14, 23:26)", -1))
}
Output:
[["102:72"] ["28:17"] ["27:15"] ["24:14"] ["23:26"]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论