如何在正则表达式中插入流量计数器?



我正在尝试将流量计数器"i"插入一个简单的Reg Exp中。 通过此流程,我想验证在一串数字中是否只出现 1 种从 0 到 9 的数字。 至少 1 个数字必须与字符串内的另一个数字不同

//Example:
var myString = "2222222222222222"; //Should Output Error
var myString2 = "2222222222222228"; //Should be OK
for(var i = 0; i <= 9; i++)
{
//I'm trying here to put the 'i' inside the regular expression
var count = (myString.match(/[i]/g) || []).length;
if(count == 16)
{
console.log("ERROR!");
break;
}
}

如果您的目标是匹配 16 位数字并确保它们不完全相同,您可以使用单个正则表达式执行此操作:

//Example:
var myString = "2222222222222222"; //Should Output Error
var myString2 = "2222222222222228"; //Should be OK
var tester = /(d)1{15}/
function testString(str) {
if (tester.test(str)) {
console.log(str + " - ERROR!!!");
} else {
console.log(str + " - OK");
}
}
testString(myString);
testString(myString2);

您匹配组中的一个数字,然后查看它是否再重复 15 次。

您可以执行以下操作:

var regex = new RegExp(i, 'g');
var count = (myString.match(regex) || []).length;

应该正常工作

使用new RegExp从字符串构建正则表达式。

例如要有d[1]d[2]等... 你会做这样的事情(使用模板文字(

for(var i = 0; i <= 9; i++)
{
//I'm trying here to put the 'i' inside the regular expression
var count = (myString.match(new RegExp(`d{${i}}`, 'g') || []).length; // <-- here
if(count == 16)
{
console.log("ERROR!");
break;
}
}

或弦乐作曲

for(var i = 0; i <= 9; i++)
{
//I'm trying here to put the 'i' inside the regular expression
var count = (myString.match(new RegExp('d{' + i + '}', 'g') || []).length; // <-- here
if(count == 16)
{
console.log("ERROR!");
break;
}
}

最新更新