简体   繁体   中英

RegEx match numbers which have n repeating digits at the end

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.
ie 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)$

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); }); 

Make sure there is no digit after or before:

/[^1]1{3}$|[^2]2{3}$|[^3]3{3}$|.../gm

where the ... mean repeat for each digit. You can generate this expression with a loop quite easily, and use can use a negative look behind for the first non series digit if preferred.

fiddle .

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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