正则表达式“不是常量” Golang出错 [英] Regex "is not a constant" error in Golang

查看:379
本文介绍了正则表达式“不是常量” 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 likes int, 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆