它对于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
答案 0 :(得分:5)
编译器不会分析您的正则表达式。它在运行时完成。 函数名称“ MustCompile”的“ Compile”部分代表正则表达式的编译。