我编写了一个模式,它在Python中工作,但是当我在Go 1.9.2中运行时,它会恐慌:
panic: runtime error: invalid memory address or nil pointer dereference守则如下:
package main
import (
"regexp"
"fmt"
)
func ReHaveSlash(s string) bool {
reSlash, _ := regexp.Compile(`^\/(?!\/)(.*?)`)
a := reSlash.MatchString(s)
return a
}
func ReHaveSlashdouble(s string) bool {
reSlash, _ := regexp.Compile(`^\/\/(.*?)`)
a := reSlash.MatchString(s)
return a
}
func main() {
test_url := "/xmars-assets.qiniu.com/archives/1369"
fmt.Println(ReHaveSlashdouble(test_url))
fmt.Println(ReHaveSlash(test_url))
}控制台中的结果如下
false
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x1095e56]
goroutine 1 [running]:
regexp.(*Regexp).get(0x0, 0x0)
/usr/local/Cellar/go/1.9.2/libexec/src/regexp/regexp.go:211 +0x26
regexp.(*Regexp).doExecute(0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x10ee1f5, 0x25, 0x0, 0x0, ...)
/usr/local/Cellar/go/1.9.2/libexec/src/regexp/exec.go:420 +0x40
regexp.(*Regexp).doMatch(0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x10ee1f5, 0x25, 0xc42000a0c0)
/usr/local/Cellar/go/1.9.2/libexec/src/regexp/exec.go:412 +0xc8
regexp.(*Regexp).MatchString(0x0, 0x10ee1f5, 0x25, 0x115f400)
/usr/local/Cellar/go/1.9.2/libexec/src/regexp/regexp.go:435 +0x6c
main.ReHaveSlash(0x10ee1f5, 0x25, 0x1)
/Users/l2017006/Documents/work/check-link/test_re.go:12 +0x58
main.main()
/Users/l2017006/Documents/work/check-link/test_re.go:29 +0xa5发布于 2018-02-27 09:52:28
Go regexp不支持观看。您可以在这里使用带有替换组的否定式字符类来解决这个问题:
package main
import (
"regexp"
"fmt"
)
func ReHaveSlash(s string) bool {
var reSlash = regexp.MustCompile(`^/([^/].*|$)`)
return reSlash.MatchString(s)
}
func ReHaveSlashdouble(s string) bool {
var reSlash = regexp.MustCompile(`^//([^/].*|$)`)
return reSlash.MatchString(s)
}
func main() {
test_url := "/xmars-assets.qiniu.com/archives/1369"
fmt.Println(ReHaveSlashdouble(test_url))
fmt.Println(ReHaveSlash(test_url))
}^/([^/].*|$)模式在字符串的开头匹配一个/,然后匹配除/之外的字符,后面跟着任何0+字符或字符串的末尾。^//([^/].*|$)与//匹配,后面跟着任何0+字符或字符串的结尾
如果要确保只匹配同一行上的字符串,请将[^/]替换为[^/\r\n],因为[^/]也匹配换行。
发布于 2018-02-27 09:41:45
Go regex不支持旁观者。
这将返回一个错误,但忽略它:
reSlash, _ := regexp.Compile(`^\/(?!\/)(.*?)`)错误解析regexp:无效或不支持Perl语法:
(?!
使用此服务测试正则表达式的Golang:https://regex-golang.appspot.com/assets/html/index.html
https://stackoverflow.com/questions/49005416
复制相似问题