Search code examples
gocompiler-errorsgo-build

Why does go build succeed for a regexp.MustCompile parsing error?


It fails for go run or go test (compile then run), but not for go build (compile only). I would have thought MustCompile relates to compilation, not runtime.


package main

import (
    "regexp"
)

var someInvalidRegex = regexp.MustCompile(`(?!`)

func main() {
    someInvalidRegex.MatchString("foo")
}

Runtime fail:

$ 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

Compilation success:

$ go build -o foo
$ echo $?
0

Runtime fail again:

$ ./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

Solution

  • Compiler does not analyze your regular expression. It is done in runtime. "Compile" part of "MustCompile" function name stands for the compilation of the regular expression.