ds3016
2018-07-31 14:56
浏览 476
已采纳

为什么要为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

图片转代码服务由CSDN问答提供 功能建议

对于 go run go test (编译)失败 然后运行),但不能用于 go build (仅编译)。 我本以为 MustCompile 与编译有关,而不是与运行时有关。


  包main 
 
import(
“ regexp” 
)
 
var someInvalidRegex = regexp.MustCompile(`(?!`)
 
func main(){
 someInvalidRegex.MatchString(“ foo”)\  n} 
   
 
 

运行时失败:

  $ go main.go 
panic:regexp:编译 (`(?!`):解析正则表达式时出错:无效或不受支持的Perl语法:`(?!`
 
goroutine 1 [正在运行]:
regexp.MustCompile(0x10b7d19,0x3,0xc420022070)
 / usr / local / 地窖/go/1.10.3/libexec/src/regexp/regexp.go:240 + 0x171 
exit状态2 
   
 
 

编译成功:

  $ go build -o foo 
 $ echo $?
0 
   
 
 

运行时再次失败:

  $ ./foo
panic:regexp:Compile(`(?!`):解析regexp时出错:无效或不受支持的Perl语法:`(?!`
 
goroutine 1  [运行中]:
regexp.MustCompile(0x10b7d19,0x3,0xc420022070)
 /usr/local/Cellar/go/1.10.3  /libexec/src/regexp/regexp.go:240 + 0x171 
   
 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • 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.

    点赞 评论

相关推荐 更多相似问题