我想创建一个“类”来处理输入验证。首先,我将其类型Input
存储为用户输入的字符串,并将REGP
其存储正则表达式模式和该模式的描述。我创建了两个常量实例REGP_LOGINNAME
和REGP_PASSWORD
。但是我得到了错误const initializer REGP literal is not a constant
。为什么?
package aut
import "regexp"
type Input string
type REGP struct {
pattern string
Descr string
}
const REGP_LOGINNAME = REGP{ //const initializer REGP literal is not a constant
"regex pattern 1",
"regex description 1",
}
const REGP_PASSWORD = REGP{ //const initializer REGP literal is not a constant
"regex pattern 2",
"regex description 2",
}
func (i Input) isMatch(regp REGP) bool {
isMatchREGP, _ := regexp.MatchString(regp.pattern, string(i))
return isMatchREGP
}
错误信息:
/usr/local/go/bin/go build -i [/home/casper/gopath/codespace_v2.6.6/dev/server_side/golang/go_codespace_v2.1/server/lib/aut]
# _/home/casper/gopath/codespace_v2.6.6/dev/server_side/golang/go_codespace_v2.1/server/lib/aut
./validation.go:15: const initializer REGP literal is not a constant
./validation.go:20: const initializer REGP literal is not a constant
Error: process exited with code 2.
在Go Consants只能是标量值(例如2
,true
,3.14
,"and more"
),或者仅由常量的任何表达(例如1 + 2
,"hello " + "world"
或2 * math.Pi * 1i
)。
这意味着REGP_LOGINNAME
不能将非标量值的结构类型(例如your)分配给常量。而是使用变量:
var (
REGP_LOGINNAME = REGP{
pattern: `/^(?=^.{6,20}$)^[a-zA-Z][a-zA-Z0-9]*[._-]?[a-zA-Z0-9]+$/`,
Descr: "regex description 1",
}
REGP_PASSWORD = REGP{
pattern: `/^(?=^.{8,}$)(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s)[0-9a-zA-Z!@#$%^&*()]*$/`,
Descr: "regex description 2",
}
)
除了:我当然不知道您的用例,但是我真的很怀疑您实际上是否需要或想使用正则表达式来验证用户密码。相反,可以考虑通过PRECIS的OpaqueString配置文件(用于处理和加强unicode字符串安全性的框架;不透明的字符串配置文件旨在处理密码)传递它。同样,UsernameCaseMapped和UsernameCasePreserved配置文件(也在链接包中实现)可用于用户名,以确保您不会以看起来相同但具有不同Unicode字符的两个用户名结尾。当然,也可以进行进一步的验证。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句