我想验证一个字符串,例如名称。没有空格的字符串。对于正常的 Ascii,以下正则表达式就足够了“^\w+$”,其中 ^ 和 $ 考虑整个字符串。我尝试使用 \pL 字符类对 unicode 字符实现相同的结果以支持多种语言。但由于某种原因 $ 无法帮助匹配字符串结尾。我究竟做错了什么?go版本go1.12.5 darwin/amd64package mainimport ( "fmt" "regexp")func main() { // Unicode character class fmt.Println(regexp.MatchString(`^\pL+$`, "testuser")) // expected true fmt.Println(regexp.MatchString(`^\pL+$`, "user with space")) // expected false // Hindi script fmt.Println(regexp.MatchString(`^\pL+$`, "सकता")) // expected true doesn't match end of line // Hindi script fmt.Println(regexp.MatchString(`^\pL+`, "सकता")) // expected true // Chinese fmt.Println(regexp.MatchString(`^\pL+$`, "我能")) // expected true //French fmt.Println(regexp.MatchString(`^\pL+$`, "ægithaleshâtifs")) // expected true }actual result:true <nil>false <nil>false <nil>true <nil>true <nil>true <nil>expected result:true <nil>false <nil>true <nil>true <nil>true <nil>true <nil>
1 回答
慕盖茨4494581
TA贡献1850条经验 获得超11个赞
您可以使用
^[\p{L}\p{M}]+$
细节
^
- 字符串的开头[
- 匹配的字符类的开始\p{L}
- 任何BMP字母\p{M}
- 任何变音符号
]+
- 角色课程结束,重复1次以上$
- 字符串末尾。
_
如果您还计划匹配数字\w
,请将它们添加到字符类中,^[\p{L}\p{M}0-9_]+$
或者^[\p{L}\p{M}\p{N}_]+$
.
- 1 回答
- 0 关注
- 90 浏览
添加回答
举报
0/150
提交
取消