Golang glob错误匹配非目标路径段问题咨询
问题原因与解决方法
你遇到的问题是因为github.com/gobwas/glob库默认的*通配符会匹配任意字符(包括路径分隔符/),所以模式中的*会贪婪匹配hedwig/another这部分内容,导致不符合预期的路径也被判定为匹配。
解决方法
有两种方式可以实现你想要的“*仅匹配单个路径段(不跨目录)”的效果:
方法1:使用[^/]*替代*
直接修改glob模式,用[^/]*明确限制匹配内容不包含/,这样就只会匹配单个目录名:
package main import ( "fmt" "github.com/gobwas/glob" ) func main() { ptrn := "/users/[^/]*/path/to/program.exe" // 修改此处的*为[^/]* filep := "/users/hedwig/another/path/to/program.exe" g := glob.MustCompile(ptrn) fmt.Println(g.Match(filep)) // 输出false }
方法2:启用WithSingleStar选项
编译glob模式时传入glob.WithSingleStar()选项,让默认的*仅匹配单个路径段(不包含/):
package main import ( "fmt" "github.com/gobwas/glob" ) func main() { ptrn := "/users/*/path/to/program.exe" filep := "/users/hedwig/another/path/to/program.exe" // 启用WithSingleStar选项 g := glob.MustCompile(ptrn, glob.WithSingleStar()) fmt.Println(g.Match(filep)) // 输出false }
这两种方式都能让你的glob模式只匹配/users/xxx/path/to/program.exe这类单层级目录的路径,拒绝包含额外子目录的路径。
内容的提问来源于stack exchange,提问作者Amit Shani
相关产品推荐
相关产品推荐

