gpt4 book ai didi

javascript - 正则表达式允许中文或字母字符

转载 作者:行者123 更新时间:2023-11-30 19:41:34 25 4
gpt4 key购买 nike

  • 我尝试允许输入中文或字母字符。

     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));

关于javascript - 正则表达式允许中文或字母字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55331609/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com