首页 > 解决方案 > 正则表达式允许中文或字母字符

问题描述

预期结果 :

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.

标签: javascriptregex

解决方案


您的汉字字符类范围似乎是正确的,至少从这里的简单本地测试来看是正确的。但是,我看到这两种模式的另一个问题,因为\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));


推荐阅读