Reputation: 116
I want to match numbers which have exact n repeating digits at the end in Javascript. However, my regex matches n or more than n digits at the end, and I can't seem to fix that.
i.e n=3, match these:
12333
222
1233334333
Not match these:
11
12344
122233
123333
My regexs(don't work):
(\d)\1{2}$
[^\1](\d)\1{2}$
(\d){3}(?!\1)$
Upvotes: 2
Views: 107
Reputation: 415
While this expression is almost resolve you need (it gives false positive for 4 or more repetitions) and maybe this can be fixed too ... i suggest to solve this with no or not only with regex. Maybe a [0-9]{n} and an exact repetition check with a backward loop on the string.
let re= /1{3}$|2{3}$|3{3}$|4{3}$|5{3}$|6{3}$|7{3}$|8{3}$|9{3}$|0{3}$/;
var div = document.getElementById('out');
div.innerHTML += "12333".match(re)+" -- <br/>"
div.innerHTML += "222".match(re) +" -- <br/>"
div.innerHTML += "1233334333".match(re) +" -- <br/>"
// Not match these:
div.innerHTML += "11".match(re) +" -- <br/>"
div.innerHTML += "12344".match(re) +" -- <br/>"
div.innerHTML += "122233".match(re)+" -- <br/>"
div.innerHTML += "123333".match(re)+" -- <br/>"
<div id=out></div>
Upvotes: 0
Reputation: 370689
Try this - match the digit right before the repeating digits start, use negative lookahead for said digit, then match 3 repeating digits:
const strs = [
'12333',
'222',
'1233334333',
'11',
'12344',
'123333'];
const re = /(^|(\d)(?!\2))(\d)\3{2}$/;
strs.forEach(str => {
if (re.test(str)) console.log('pass ' + str);
});
Upvotes: 3