RandomUser
RandomUser

Reputation: 1853

Regular Expression to deny input of repeated characters

I want a regular expression which allows the uses to enter the following values. Minimum of Four and max of 30 characters and first character should be Upper Case.

Eg: John, Smith, Anderson, Emma

And I don't want the user to input the following types of values

Jooohnnnnnn, Smmmmith, Aaaanderson, Emmmmmmmmma

Can any one provide me with a regular expression? I search for quite some time but can't find working RegEx.

I need it for my ASP.net MVC application Model validation.

Thanks

Edited: I don't know how to check for repeated characters I just tried the following

@"^[A-Z]{1}[a-zA-Z ]{2,29}$"

The rules that I would like to add are

  1. First character Upper case
  2. 4-30 characters
  3. No repeats of characters. Not greater than 2

Upvotes: 3

Views: 2424

Answers (2)

Pierluc SS
Pierluc SS

Reputation: 3176

Here is what you are looking for:

^               (?# Starting of name)
 (?=[A-Z])      (?# Ensure it starts with capital A-Z without consuming the text)
 (?i:([a-z])    (?# Following letters ignoring case)  
    (?!\1{2,})  (?# Letter cant be followed by previous letter more than twice)
 ){3,30}        (?# Allow condition to be repeated 3 to 30 times)
$  

Visual representation would look like follow:

Regular expression visualization

Upvotes: 3

Robin
Robin

Reputation: 9644

To perform a check on your regex you can use a negative look ahead:

^(?!.*(.)\1{2})[A-Z][a-zA-Z ]{3,29}$

The look ahead (?!...) will fail the whole regex if what's inside it matches.

To look for repeated patterns, we use a capture group: (.)\1{2}. We capture the first character, then check if it is followed by (at least) two identical characters with the backreference \1.

See demo here.

Upvotes: 7

Related Questions