我想验证一个字符串例如名称。没有空格的字符串。对于普通的Ascii,以下正则表达式足以满足"^\w+$"的要求,其中^和$将整个字符串考虑在内。我尝试使用\pL字符类为Unicode字符实现相同的结果,以支持多种语言。但是由于某种原因,$不能帮助匹配字符串的结尾。我究竟做错了什么?
代码示例在这里:https://play.golang.org/p/SPDEbWmqx0N
我从以下位置复制粘贴的随机字符:http://www.columbia.edu/~fdc/utf8/
转到版本go1.12.5 darwin/amd64
package main
import (
"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>
分析解答
您可以使用
^[\p{L}\p{M}]+$
参见去demo。
细节
^
-字符串开始[
-匹配的字符类的开始-
\p{L}
-任何BMP字母 \p{M}
-任何变音符
-
]+
-字符类的结尾,重复1次以上$
-字符串结尾。
如果打算像\w
一样匹配数字和_
,则将它们添加到字符类^[\p{L}\p{M}0-9_]+$
或^[\p{L}\p{M}\p{N}_]+$
中。