I am trying to check the username whether is only containing alphabetic characters. What is the idiomatic way to check it in Go?
4条回答 默认 最新
- dongpangbu4016 2016-07-24 08:55关注
you may use
unicode.IsLetter
like this working sample code:package main import "fmt" import "unicode" func IsLetter(s string) bool { for _, r := range s { if !unicode.IsLetter(r) { return false } } return true } func main() { fmt.Println(IsLetter("Alex")) // true fmt.Println(IsLetter("123")) // false }
or if you have limited range e.g. 'a'..'z' and 'A'..'Z', you may use this working sample code:
package main import "fmt" func IsLetter(s string) bool { for _, r := range s { if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') { return false } } return true } func main() { fmt.Println(IsLetter("Alex")) // true fmt.Println(IsLetter("123 a")) // false }
or if you have limited range e.g. 'a'..'z' and 'A'..'Z', you may use this working sample code:
package main import "fmt" import "regexp" var IsLetter = regexp.MustCompile(`^[a-zA-Z]+$`).MatchString func main() { fmt.Println(IsLetter("Alex")) // true fmt.Println(IsLetter("u123")) // false }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥20 双硬盘安装Ubuntu后windows 无法挂载硬盘
- ¥15 帮我利用jupyter 运行一个正确的代码
- ¥15 如何使用Gephi软件和Python包中的GephiStreamer交互
- ¥15 sqlite加密问题咨询
- ¥15 appdesigner接收不到udp组播的数据
- ¥15 verilog 非阻塞赋值下的移位拼接错误
- ¥100 两个按钮控制一个LED
- ¥15 用C语言写离散数学相关问题
- ¥30 如何用python的GephiStreamer连接到gephi中,把Python和Gephi的具体操作过程都展示,重点回答Gephi软件的调试,以及如果代码的端口在浏览器中无法显示怎么处理
- ¥15 ansys机翼建模肋参数