正则表达式检查该字符串包含混合字符:0-n个数字和0-m的信

问题描述 投票:1回答:2

我试图找到正则表达式,让我通过具有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]");
javascript regex
2个回答
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-2个出现的任何0+比其他数字字符,然后一个数字,然后0+字符以外位数的结束串
  • (?=(?:[^a-z]*[a-z]){0,3}[^a-z]*$) - 积极前瞻,需要立即到当前位置的右边,有0到2比出现小写ASCII字母,然后一个数字以外的任何字符0+,然后0+字符不是小写ASCII字母到其他该字符串的结尾
  • [a-z0-9]* - 0或多个小写ASCII字母或数字
  • $ - 字符串的结尾

4
投票

而不是单一的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]");
© www.soinside.com 2019 - 2024. All rights reserved.