正则表达式“不是常量” Golang出错 [英] Regex "is not a constant" error in Golang
问题描述
我试图在Golang中编写一个正则表达式来验证一个字符串只有字母数字,句点和下划线。然而,我遇到了一个我从未见过的错误,并且在谷歌搜索中一直没有成功。
这是正则表达式:
pattern = regexp.MustCompile(`^ [A-Za-z0-9_\。] +`)
这是错误:
const initializer regexp .MustCompile(^ [A-Za-z0-9_\\。] +)不是常量
不是常数是什么意思,我该如何解决这个问题?
谢谢。解决方案当你试图分配一个不能保持常量的类型的变量时(例如,
Regexp
),通常会发生这种情况。 。只有像int
,string
等基本类型可以是常量。详情请参阅 。
示例:
pattern = regexp.MustCompile(`^ [A-Za-z0-9_\。] + `)
//转换为:
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_\。] +`)
I'm trying to write a regex in Golang to verify that a string only has alphanumerics, periods, and underscores. However, I'm running into an error that I haven't seen before and have been unsuccessful at Googling.
Here's the regex:
pattern = regexp.MustCompile(`^[A-Za-z0-9_\.]+`)
Here is the error:
const initializer regexp.MustCompile("^[A-Za-z0-9_\\.]+") is not a constant
What does "not a constant" mean and how do I fix this?
Thanks.解决方案This typically happens when you're trying to assign to a package-level variable that has a type that can't be constant (like for example,
Regexp
). Only basic types likesint
,string
, etc. can be constant. See here for more details.Example:
pattern = regexp.MustCompile(`^[A-Za-z0-9_\.]+`) // which translates to: const pattern = regexp.MustCompile(`^[A-Za-z0-9_\.]+`)
You have to declare it as a
var
for it to work:var pattern = regexp.MustCompile(`^[A-Za-z0-9_\.]+`)
In addition, I usually put a note to say that the variable is treated as a constant:
var /* const */ pattern = regexp.MustCompile(`^[A-Za-z0-9_\.]+`)
这篇关于正则表达式“不是常量” Golang出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!