-3

它失败了go runor 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
4

1 回答 1

5

编译器不会分析您的正则表达式。它是在运行时完成的。“MustCompile”函数名的“Compile”部分代表正则表达式的编译。

于 2018-07-31T15:00:40.137 回答