为何在使用 regexp.MustCompile 时 go build 却没有报错?
时间:2024-03-24
浏览:322
作者:佚名
在使用 `regexp.MustCompile` 函数时,`go build` 不会报错,但 `go run` 或 `go test` 会失败。这是因为编译器不会分析正则表达式,而是在运行时完成的。因此,在编译时不会检测到正则表达式中的错误,而是在运行时引发 panic。
问题内容
对于 go run 或 go test (编译然后运行)失败,但对于 go build (仅编译)失败。我本以为 mustcompile 与编译有关,而不是运行时。
package main
import (
"regexp"
)
var someinvalidregex = regexp.mustcompile(`(?!`)
func main() {
someinvalidregex.matchstring("foo")
}
运行时失败:
$ go run main.go
panic: regexp: compile(`(?!`): error parsing regexp: invalid or unsupported perl syntax: `(?!`
goroutine 1 [running]:
regexp.mustcompile(0x10b7d19, 0x3, 0xc420022070)
/usr/local/cellar/go/1.10.3/libexec/src/regexp/regexp.go:240 +0x171
exit status 2
编译成功:
$ go build -o foo $ echo $? 0
运行时再次失败:
$ ./foo
panic: regexp: Compile(`(?!`): error parsing regexp: invalid or unsupported Perl syntax: `(?!`
goroutine 1 [running]:
regexp.MustCompile(0x10b7d19, 0x3, 0xc420022070)
/usr/local/Cellar/go/1.10.3/libexec/src/regexp/regexp.go:240 +0x171解决方案
编译器不会分析您的正则表达式。它是在运行时完成的。 “MustCompile”函数名中的“Compile”部分代表正则表达式的编译。
文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《为何在使用 regexp.MustCompile 时 go build 却没有报错?》文章吧,也可关注golang学习网公众号了解相关技术文章。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
12.01
热门专题
