ds3016
2018-07-31 14:56 阅读 262
已采纳

为什么要为regexp.MustCompile解析错误进行构建成功?

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
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dongqi0644 dongqi0644 2018-07-31 15:00

    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.

    点赞 评论 复制链接分享

相关推荐