我想驗證一個字符串,例如名稱。沒有空格的字符串。對于正常的 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 關注
- 156 瀏覽
添加回答
舉報
0/150
提交
取消