简体   繁体   中英

Regex with no consecutive letters and numbers

I have a requirement to make a regex that verifies the following points for an alphanumeric string in Swift and I have no clue on how to achieve them:

  • No more than 4 consecutive alphabetic or numeric characters

    (eg 12345a or 1abcde would be wrong but 123a45 or abcd1e would be correct)

  • No more than 4 of the same alphanumeric characters

    (eg 111a11 or aaaa1a would be wrong)

  • Exactly 6 characters

Help would be greatly appreciated, thanks.

As pointed out by others, your second requirement is hard to accomplish with regular expressions alone while the first and third can be done with:

^
(?!\D*\d{5,}\D*)
(?![^A-Za-z]*[A-Za-z]{5,}[^A-Za-z]*)
.{6}
$

See a demo on regex101.com .

To do the whole job, in each simple step: Note: This is a javascript solution but you could translate to your language of choice following the same logic:

var str = "ss4sss";

fnTest = function(str){
  var isValid = true;


  if(/\d{5,}/.test(str)){// no more than 4 consecutive numeric chars
    return false;
  }else if(/[a-z]{5,}/i.test(str)){// no more than 4 consecutive alpha chars
    return false;
  }else if(str.length !== 6){// not 6 characters
    return false;    
  }else{ // any character used more than 4 times
    var reg = /([\w\W])/g;
    var arrM ;
    var obj = {};
    while(arrM = reg.exec(str)){
      var letter = arrM[1];
      if(!obj[letter]){
        obj[letter] = 0;
      }
      obj[letter]++;

      if(obj[letter] > 4){    
        isValid = false;
        break;
      }
    }
  }
  return isValid;
}
fnTest(str);

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