javascript - 正则表达式允许中文或字母字符
问题描述
我试图允许输入中文或字母字符。
var name="TEXT" //here input either alphabetic or Chinese Characters 请输入 let reqChinesePos=/^[\u3000\u3400-\u4DBF\u4E00-\u9FFF]\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 = /^[\u3000\u3400-\u4DBF\u4E00-\u9FFF\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));
推荐阅读
- python - 在同一张量纤维中不止一个为真
- windows - Octave 中的奇怪问题:`char(97)` 未在控制台中显示结果
- swift - 在swift中使用present时如何阻止ViewController闪烁
- django - 为什么我无法通过 gitlab CI 更新我的 heroku 应用程序
- oracle - 验证时隐藏的堆叠画布
- python - 有没有办法在 Python 3 中将卸载程序写入程序并自行删除?
- python - Pandas - 将 groupBy 的平均值添加到未分组的列
- powershell - 如何通过 PowerShell 获取 Microsoft Teams 使用报告
- java - 返回集合的最佳迭代器类型?分离器,流?
- reactjs - 我想将映射的 offerid 发送到子组件