Search code examples
.netregexcriteria

.NET Regular Expression allow 3 repeated characters


I'm trying to create a .NET regular expression with the following criteria below but no go. All I have is the regular expression below. Any help would be greatly appreciated!!

  1. 8-15 characters (alpha or numeric and not case sensitive)
  2. maximum of 3 repeated characters or numbers allowed
  3. No special characters or symbols

This is what I've got:

^(?=.*[0-9].*)(?=.*[A-Za-z].*)([0-9A-Za-z]\1{3}){8,15}$

Solution

  • This regex will work

    ^(?=.{8,15}$)(?!.*?(.)\1{3})[A-Za-z0-9]+$
    

    Regex Demo

    Regex Breakdown

    ^ #Start of string
    (?=.{8,15}$) #Lookahead to check there are 8 to 15 digits
    (?!.*?(.)\1{3}) #Lookahead to determine that there is no character repeating more than thrice
    [A-Za-z0-9]+ #Match the characters
    $ #End of string
    

    For unicode support, you can use

    ^(?=.{8,15}$)(?!.*?(.)\1{3})[\p{L}\p{N}]+$
    

    NOTE :- For matching one character and one digit, you can use

    ^(?=.{8,15}$)(?=.*[A-Za-z])(?=.*\d)(?!.*?(.)\1{3})[A-Za-z0-9]+$
    

    Regex Demo