我尝试找到允许我传递包含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]");
答案 0 :(得分:4)
考虑使用全局标志分别测试字母和数字,而不是单个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]");
或者,更罗y,但也许更优雅,而不创建空的中间数组:
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]");
答案 1 :(得分:1)
可以使用一个正则表达式来实现:
let n=2,m=3;
let s=["32abc","abc32","a3b2c","3abc2","a2","abcd23","a2b3c4","aa","32", "a3b_2c"];
let rx = new RegExp(
"^" + // Start of string
"(?=(?:[^0-9]*[0-9]){0," + n + "}[^0-9]*$)" + // only 0 to n digits
"(?=(?:[^a-z]*[a-z]){0," + m + "}[^a-z]*$)" + // only 0 to m letters
"[a-z0-9]*" + // only allow 0 or more letters/digits
"$" // End of string
);
let r=s.map(x=> rx.test(x));
console.log("current is:", JSON.stringify(r));
console.log("shoud be: [true,true,true,true,true,false,false,true,true,false]");
请参见regex demo。
详细信息
^
-字符串的开头(?=(?:[^0-9]*[0-9]){0,2}[^0-9]*$)
-一个正向的超前查询,需要立即在当前位置的右边,出现零到两次出现的除数字之外的任何0+个字符,然后再出现一个数字,然后是0+个其他字符比数字到字符串末尾(?=(?:[^a-z]*[a-z]){0,3}[^a-z]*$)
-一个正向的超前查询,需要立即在当前位置的右边出现零到两次出现的任意0+字符,除了小写ASCII字母,然后是一个数字,然后是0+字符串末尾的小写ASCII字母以外的其他字符[a-z0-9]*
-0个或更多小写ASCII字母或数字$
-字符串结尾