Home > OS >  RegEx minimum 4 characters with no repetition
RegEx minimum 4 characters with no repetition

Time:05-12

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!@#$&()\-`. ,"]

CodePudding user response:

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

  • Related