简体   繁体   中英

Regex for No more than 2 consecutive numbers No more than 2 repeated characters?

I am looking to create a regex with conditions:

  • Minimum length 6
  • At least one number and one letter must be used
  • No more than 2 consecutive numbers (like 123)
  • No more than 2 repeated characters

What I am able to achieve

/^(?!.*([A-Za-z0-9!@#$&()\\-`.+,/?"])\1{2})(?=.*[a-z])(?=.*\d)[A-Za-z0-9!@#$&()\\-`.+,/?"]+$/

This validates that the string has at least one number and one letter. Instead of consecutive numbers 123, it checks 111. and i am not able to add 4th condition in this.

Any further help will be appreciated. Thanks in advance.

Try this Regex:

^(?=[\D]*\d)(?=[^a-zA-Z]*[a-zA-Z])(?=.{6,})(?!.*(\d)\1{2})(?!.*([a-zA-Z])(?:.*?\2){2,}).*$

Demo

Explanation:

  • ^ - start of the string
  • (?=[\\D]*\\d) - positive lookahead - checks for the presence of a digit
  • (?=[^a-zA-Z]*[a-zA-Z]) - positive lookahead - checks for the presence of a letter
  • (?=.{6,}) - positive lookahead - checks for the presence of atleast 6 literals
  • (?!.*(\\d)\\1{2}) - Negative lookahead - Checks for the ABSENCE of 3 consecutive digits. It will allow 2 consecutive digits though. If you do not want even 2 consecutive digits, then remove {2} from this part
  • (?!.*([a-zA-Z])(?:.*?\\2){2,}) - Negative lookahead - validates that no letter should be present more than 2 times in the string
  • .* - capture the string
  • $ - end of the string

OUTPUT:

jj112233         -Matches as it has atleast one letter, digit. Not more than 2 consecutive digits/letter. Has atleast 6 characters
jkhsfsndbf8uwwe  -matches 
a1234            -does not match as length<6 
nsds312          -matches
111aaa222        -does not match as it has more than 2 consecutive digits and also more than 2 repeated letters 
aa11bbsd         -match
hgshsadh12       -does not match as it has more than 2 `h`
hh8uqweuu        -does not match as it has more than 2 `u`

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