Pablo Mosby
Pablo Mosby

Reputation: 319

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.

I have looked through some other questions, and the suggestion they make is this one /([0-9]{5}\1)/. But this one matches any 5 numbers together.

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.

Is there any way to achieve this via regex or should I make a loop for all values?

Expected outputs:

112113 false

911111 true

112111 false

222223 true

Upvotes: 0

Views: 917

Answers (2)

ellipsis
ellipsis

Reputation: 12152

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. 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

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)

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163277

Your pattern ([0-9]{5}\1) uses a backreference to a group that does not exist yet.

In Javascript you will match 5 consecutive digits as according to the documentation stated at the link to the backreference

According to the official ECMA standard, a backreference to a non-participating capturing group must successfully match nothing..

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.

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

Regex demo

Upvotes: 3

Related Questions