ChandrasekarG ChandrasekarG - 6 months ago 39
Javascript Question

RegEx to match characters of same type

I need a regular expression that cannot contain more than 3 consecutive characters of same type

ABC - valid
@@@ - valid
123 - valid
ABCD - not valid
ABC!@# - valid



if (!/[a-z]{4}|\d{4}|[^a-z\d]{4}/i.test(s)) { console.log("valid"); } 

See the regex demo

The /[a-z]{4}|\d{4}|[^a-z\d]{4}/i regex will match in case insensitive way (due to /i) 4 consecutive ASCII letters ([a-z]{4}) or 4 consecutive digits (\d{4}), or 4 chars other than ASCII letters and digits ([^a-z\d]{4}).

The !/regex/.test() check will return false whenever the match is found.

var strs = ['ABC','@@@','123','ABC!@#','ABCD'];
var rx = /[a-z]{4}|\d{4}|[^a-z\d]{4}/i;
for (var s of strs) {
  if (!rx.test(s)) {
    console.log(s, ": valid"); 
  }  else  {
     console.log(s, ": invalid");