javascript - 用于检查字符串是否包含混合字符的正则表达式:0-n 个数字和 0-m 个字母
问题描述
我尝试找到允许我传递具有 0-n 个数字和 0-m 个小写字母的字符串的正则表达式,其中字母和数字可以混合。不允许使用任何其他字符。据我所知,不知道如何让“混合”工作
// example n and m values and array with input strings to test
let n=2,m=3;
let s=["32abc","abc32","a3b2c","3abc2","a2","abcd23","a2b3c4","aa","32","a3b_2c"];
let r=s.map(x=>/[0-9]{2}[a-z]{3}/.test(x));
console.log("curr:", JSON.stringify(r));
console.log("shoud be: [true,true,true,true,true,false,false,true,true,false]");
解决方案
考虑使用全局标志分别测试字母和数字,而不是单个 RE,并分别检查全局匹配数组的长度是否为n
和m
:
let n = 2,
m = 3; // example n and m values
let s = ["32abc", "abc32", "a3b2c", "3abc2", "a2", "abcd23", "a2b3c4", "aa", "32"];
let r = s.map(str => (
/^[0-9a-z]*$/.test(str) &&
(str.match(/[0-9]/g) || []).length <= n &&
(str.match(/[a-z]/g) || []).length <= m
));
console.log("current is:", JSON.stringify(r));
console.log("shoud be: [true,true,true,true,true,false,false,true,true]");
或者,更冗长但也许更优雅,不创建一个空的中间数组:
let n = 2,
m = 3; // example n and m values
let s = ["32abc", "abc32", "a3b2c", "3abc2", "a2", "abcd23", "a2b3c4", "aa", "32"];
let r = s.map((str, i) => {
const numMatch = str.match(/[0-9]/g);
const numMatchInt = numMatch ? numMatch.length : 0;
const alphaMatch = str.match(/[a-z]/g);
const alphaMatchInt = alphaMatch ? alphaMatch.length : 0;
return numMatchInt <= n && alphaMatchInt <= m && /^[0-9a-z]*$/.test(str);
});
console.log("current is:", JSON.stringify(r));
console.log("shoud be: [true,true,true,true,true,false,false,true,true]");
推荐阅读
- pytorch - 了解“RuntimeError:叶变量已移至图形内部”背后的原因
- r - rstudio cloud integer64 (boolean) to string
- vb.net - Dynamic For Next Loops
- css - 将 css-loader 更新到 v4 后无法解析“/images/bg.jpg”
- opencv - open cv shows green screen on jetson nano
- excel - 添加发件人电子邮件地址
- r - 从全局环境中的对象获取 colnames(具有特定模式),然后返回新的
- r - R reactable - 扩展/取消分组由 groupBy() 创建的单个项目组
- c# - 没有为重载的模拟方法引发回调
- google-mlkit - 改进 MLKit 对象检测