我试图在GO中编写一个正则表达式,以验证字符串是否只有字母数字、句点和下划线.然而,我遇到了一个我以前从未见过的错误,在谷歌上搜索也没有成功.
下面是regex:
pattern = regexp.MustCompile(`^[A-Za-z0-9_\.]+`)
以下是错误:
const initializer regexp.MustCompile("^[A-Za-z0-9_\\.]+") is not a constant
"不是常量"是什么意思?我如何解决这个问题?
我试图在GO中编写一个正则表达式,以验证字符串是否只有字母数字、句点和下划线.然而,我遇到了一个我以前从未见过的错误,在谷歌上搜索也没有成功.
下面是regex:
pattern = regexp.MustCompile(`^[A-Za-z0-9_\.]+`)
以下是错误:
const initializer regexp.MustCompile("^[A-Za-z0-9_\\.]+") is not a constant
"不是常量"是什么意思?我如何解决这个问题?
当您试图为类型不能为常量(例如,Regexp
)的常量赋值时,就会发生这种情况.只有基本类型(如int
、string
等)可以是常量.有关更多详细信息,请参见here.
示例:
pattern = regexp.MustCompile(`^[A-Za-z0-9_\.]+`)
// which translates to:
const pattern = regexp.MustCompile(`^[A-Za-z0-9_\.]+`)
您必须将其声明为var
才能工作:
var pattern = regexp.MustCompile(`^[A-Za-z0-9_\.]+`)
此外,我通常会注明变量被视为常量:
var /* const */ pattern = regexp.MustCompile(`^[A-Za-z0-9_\.]+`)