我想驗(yàn)證一個(gè)字符串,例如名稱。沒有空格的字符串。對于正常的 Ascii,以下正則表達(dá)式就足夠了“^\w+$”,其中 ^ 和 $ 考慮整個(gè)字符串。我嘗試使用 \pL 字符類對 unicode 字符實(shí)現(xiàn)相同的結(jié)果以支持多種語言。但由于某種原因 $ 無法幫助匹配字符串結(jié)尾。我究竟做錯(cuò)了什么?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貢獻(xiàn)1850條經(jīng)驗(yàn) 獲得超11個(gè)贊
您可以使用
^[\p{L}\p{M}]+$
細(xì)節(jié)
^
- 字符串的開頭[
- 匹配的字符類的開始\p{L}
- 任何BMP字母\p{M}
- 任何變音符號
]+
- 角色課程結(jié)束,重復(fù)1次以上$
- 字符串末尾。
_
如果您還計(jì)劃匹配數(shù)字\w
,請將它們添加到字符類中,^[\p{L}\p{M}0-9_]+$
或者^[\p{L}\p{M}\p{N}_]+$
.
- 1 回答
- 0 關(guān)注
- 155 瀏覽
添加回答
舉報(bào)
0/150
提交
取消