简体   繁体   English

检查是否有任何数字单独重复超过 N 次

[英]Check if any number is repeated, individually, more than N times

What I want to check is if there is any number repated more than 5 times with a regex.我要检查的是是否有任何数字被正则表达式重复超过 5 次。

I have looked through some other questions, and the suggestion they make is this one /([0-9]{5}\1)/ .我查看了其他一些问题,他们提出的建议是/([0-9]{5}\1)/ But this one matches any 5 numbers together.但这一个将任何 5 个数字匹配在一起。

What I want to achieve with this regex is finding if, for example, number 1 is repeated 5 times, number 2, number 3 and so on.我想用这个正则表达式实现的是查找,例如,数字 1 是否重复 5 次、数字 2、数字 3 等等。

Is there any way to achieve this via regex or should I make a loop for all values?有没有办法通过正则表达式实现这一点,或者我应该为所有值创建一个循环?

Expected outputs:预期产出:

112113 false 112113错误

911111 true 911111

112111 false 112111错误

222223 true 222223

Your pattern ([0-9]{5}\1) uses a backreference to a group that does not exist yet.您的模式([0-9]{5}\1)使用了对尚不存在的组的反向引用

In Javascript you will match 5 consecutive digits as according to the documentation stated at the link to the backreference在 Javascript 中,您将根据反向引用链接中所述的文档匹配 5 个连续数字

According to the official ECMA standard, a backreference to a non-participating capturing group must successfully match nothing..根据官方 ECMA 标准,对非参与捕获组的反向引用必须成功匹配任何内容。

You could update your pattern to put the capturing group around matching a single digit and then repeat that 4 times to match 5 repeated digits.您可以更新您的模式以使捕获组围绕匹配单个数字,然后重复该 4 次以匹配 5 个重复数字。

([0-9])\1{4}

Regex demo正则表达式演示

You can simply use filter.您可以简单地使用过滤器。 It is faster than regex.它比正则表达式更快。 In the function input the number, the number whose repentance has to be calculated and the number of times the repetition has to be found.在 function 中输入数字,需要计算的忏悔次数和重复次数。 Convert the number to a string and split it into an array.将数字转换为字符串并将其拆分为数组。 Apply filter and for the occurrence of the number.应用过滤器和出现的数字。 It will return an array.它将返回一个数组。 If the length of the array is equal to the number of repentance than return true else false如果数组的长度等于忏悔的次数,则返回true else false

 var n = 1; var num = 1123231121; var comp = 5 function a(n, num, comp) { console.log(String(num).split('').filter(function(e) { return e == n }).length == comp) } a(n, num, comp)

if (/[^\d]\d{5}[^\d]/.test(num)) {
    //Test passed
}

this would work as a regex.这将作为一个正则表达式。

 var inputs = [ '112113', '911111', '112111', '222223' ]; inputs.forEach(function(input) { if (/[^\d]\d{5}[^\d]/.test(input)) { console.log(input); } });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM