我想预编译多个正则表达式并将引用存储在变量中,但我遇到了问题。似乎当我regexp.Compile()第二次调用该方法时,我没有得到新的参考。它指向第一个。在下面的示例中,只有 r2 应该返回“true”。每次打电话时如何获得唯一的参考regexp.Compile()?https://play.golang.org/p/KJJbytSZddJpackage mainimport ( "fmt" "regexp")func main() { r1, _ := regexp.Compile(`(/api)(/v\d+)/devices`) r2, _ := regexp.Compile(`(/api)(/v\d+)/devices/\w+`) fmt.Println(r1.MatchString("/api/v1/devices/1")) fmt.Println(r2.MatchString("/api/v1/devices/1"))}
1 回答

动漫人物
TA贡献1815条经验 获得超10个赞
我怀疑您想要以下代码。使用正则表达式锚来防止第一个匹配太多。还要在全局范围内使用 MustCompile,否则如果您在函数中使用 Compile,它将运行每个函数调用。无论如何,您都忽略了错误返回值。
https://play.golang.org/p/tj3J_PSXNu1
package main
import (
"fmt"
"regexp"
)
var r1 = regexp.MustCompile(`^(/api)(/v\d+)/devices$`)
var r2 = regexp.MustCompile(`^(/api)(/v\d+)/devices/\w+$`)
func main() {
fmt.Println(r1.MatchString("/api/v1/devices/1"))
fmt.Println(r2.MatchString("/api/v1/devices/1"))
}
- 1 回答
- 0 关注
- 174 浏览
添加回答
举报
0/150
提交
取消