Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

RegEx minimum 4 characters with no repetition

Trying to create a regex where a field should contain minimum 4 characters(only alphabets [a-zA-Z]) where

  1. first 4 alphabets should not repeat. eg aaaa,zzzz not acceptable
  2. first 4 characters should not contain space, numbers, special characters
  3. afterwhich anything is fine

I tried following expression but 1 case is failing which is (a123,a@#!):
^(?=.{1,4}$)(([a-zA-Z]){1,4}\2?(?!\2))+[a-zA-Z0-9!@#$&()\-`.+,"]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You might write the pattern as:

^(?!(.)\1{3})[a-zA-Z]{4}.*

Explanantion

  • ^ Start of string
  • (?!(.)\1{3}) Negative lookahead, assert not 4 of the same characters
  • [a-zA-Z]{4} Match 4 chars a-z A-Z
  • .* Match the rest of the line

Regex demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading