簡體   English   中英

regexp 允許中文或字母字符

[英]regexp allow chinese or alphabetic characters

  • 我試圖允許輸入中文或字母字符。

     var name="TEXT" //here input either alphabetic or Chinese Characters 請輸入let reqChinesePos=/^[\ \㐀-\䶿\一-\鿿]\\d{8}$/; let reqEnglish=/^[A-Za-z]\\d{40}$/ console.log(reqEnglish.test(name)); //Here true but here also Chinese characters also match. console.log(reqChinesePos.test(name)); //Here true but here also alphabetic characters also match.

預期結果 :

console.log(reqEnglish.test(name));//here only allow alphabetic characters not allow chinese.
console.log(reqChinesePos.test(name));//here only allow Chinese characters not allow English.

您的漢字字符類范圍似乎是正確的,至少從這里的簡單本地測試來看是這樣。 但是,我發現這兩種模式都有另一個問題,如果您想在兩種情況下都允許使用羅馬數字,那么\\d可能應該是字符類的一部分。 進行此更改后,然后為輸入提供一個寬度或寬度范圍。 假設你想要寬度都為 8,你可以嘗試:

 var reqChinesePos = /^[\ \㐀-\䶿\一-\鿿\\d]{8}$/; var reqEnglish = /^[A-Za-z\\d]{8}$/ var name1 = "大貓大貓大貓大貓"; var name2 = "JONATHAN"; var name3 = "BIGCAT大貓"; console.log(name1); console.log(reqEnglish.test(name1)); console.log(reqChinesePos.test(name1)); console.log(name2); console.log(reqEnglish.test(name2)); console.log(reqChinesePos.test(name2)); console.log(name3); console.log(reqEnglish.test(name3)); console.log(reqChinesePos.test(name3));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM