为了在不在循环内调用匿名函数和不在循环内使用“append”函数复制数组的情况下改善RAM和CPU使用情况,请参考以下示例:
你可以使用多行文本存储一个以上的子组,无需使用“+”连接字符串,也无需在循环内使用另一个循环(如此处发布的其他示例)。
txt := `2001-01-20
2009-03-22
2018-02-25
2018-06-07`
regex := *regexp.MustCompile(`(?s)(\d{4})-(\d{2})-(\d{2})`)
res := regex.FindAllStringSubmatch(txt, -1)
for i := range res {
fmt.Printf("year: %s, month: %s, day: %s\n", res[i][1], res[i][2], res[i][3])
}
输出:
year: 2001, month: 01, day: 20
year: 2009, month: 03, day: 22
year: 2018, month: 02, day: 25
year: 2018, month: 06, day: 07
注意:res[i][0] =~ match.group(0) Java
如果您想存储这些信息,请使用结构体类型:
type date struct {
y,m,d int
}
...
func main() {
...
dates := make([]date, 0, len(res))
for ... {
dates[index] = date{y: res[index][1], m: res[index][2], d: res[index][3]}
}
}
使用匿名组会更好(性能优化)
在Github上使用"ReplaceAllGroupFunc"不是一个好主意,因为:
- 它在循环内部使用了循环
- 它在循环内部调用了匿名函数
- 它的代码量很大
- 它在循环内部使用了"append"函数,这是不好的。每次调用"append"函数时,都会将数组复制到新的内存位置
Regexp.SubexpNames
中的示例。 - thwd