首页 > 解决方案 > 用于检查字符串是否包含混合字符的正则表达式: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]");

标签: javascriptregex

解决方案


考虑使用全局标志分别测试字母和数字,而不是单个 RE,并分别检查全局匹配数组的长度是否为nm

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


推荐阅读