go 判断字符串是否由英文、数字、“-”、“_”构成
在开发中遇到了判断一个字段是否由英文、数字、“-”、“_”构成的问题
找了一下好像没有发现有现成的代码或者库,所以记录一下实现方式
func isValidCode(str string) bool {
log.Println(str)
for _, ch := range str {
log.Println(ch)
if isLetter := unicode.IsLetter(ch); isLetter {
continue
} else if isDigit := unicode.IsDigit(ch); isDigit {
continue
} else if string(ch) != "-" || string(ch) != "_" {
continue
} else {
return false
}
}
return true
}
代码写的不够简洁,但是能用
最终经过测试发现是坑爹货,中文也会读进去的。
demo2
func IsValidCode(str string) bool {
match, _ := regexp.MatchString(`^[A-Za-z0-9-_]+$`, str)
return match
}
还是正则匹配靠谱点