如何匹配包含unicode字符的完整字符串?

我想验证一个字符串,例如名称。没有空格的字符串。对于正常的 Ascii,以下正则表达式就足够了“^\w+$”,其中 ^ 和 $ 考虑整个字符串。我尝试使用 \pL 字符类对 unicode 字符实现相同的结果以支持多种语言。但由于某种原因 $ 无法帮助匹配字符串结尾。我究竟做错了什么?


go版本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>


森林海
浏览 90回答 1
1回答

慕盖茨4494581

您可以使用^[\p{L}\p{M}]+$细节^- 字符串的开头[- 匹配的字符类的开始\p{L}- 任何BMP字母\p{M}- 任何变音符号]+- 角色课程结束,重复1次以上$- 字符串末尾。_如果您还计划匹配数字\w,请将它们添加到字符类中,^[\p{L}\p{M}0-9_]+$或者^[\p{L}\p{M}\p{N}_]+$.
打开App,查看更多内容
随时随地看视频慕课网APP