使用以下代码:
package main
import (
"regexp"
)
var namedMatch = regexp.MustCompile("\\{([^}]+)\\}")
func main() {
example := regexp.QuoteMeta("/book/{author-id}/{book-id}")
new_path := namedMatch.ReplaceAllString(example, `(?P<$1>[^/]+)`)
regexp.MustCompile(new_path)
}
我们得到以下恐慌:
panic: regexp: Compile(`/book/\(?P<author-id\>[^/]+)/\(?P<book-id\>[^/]+)`): error parsing regexp: unexpected ): `/book/\(?P<author-id\>[^/]+)/\(?P<book-id\>[^/]+)`
goroutine 1 [running]:
regexp.MustCompile(0xc000110040, 0x31, 0x1f)
/usr/local/go-faketime/src/regexp/regexp.go:311 +0x157
main.main()
/tmp/sandbox229373954/prog.go:13 +0x8b
为什么替换字符串会像\(?P<author-id\>[^/]+)这样\(?P<book-id\>[^/]+)被转义?不应该Regexp按原样放置字符串吗?我该如何解决这个问题才能在替换中使用有效的正则表达式?
jeck猫
相关分类