Home > Net >  Regularexpression for duplicate pattern
Regularexpression for duplicate pattern

Time:06-22

I am trying to write a regex to handle these cases

  1. contains only alphanumeric with minimum of 2 alpha characters(numbers are optional).
  2. only special character allowed is hyphen.
  3. cannot be all same letter ignoring hyphen.
  4. cannot be all hyphens
  5. cannot be all numeric

My regex: (?=[^A-Za-z]*[A-Za-z]){2}^[\w-]{6,40}$

Above regex works for most of the scenarios except 1) & 3). Can anyone suggest me to fix this. I am stuck in this.

Regards, Sajesh

CodePudding user response:

You can use

^(?!\d $)(?!- $)(?=(?:[\d-]*[A-Za-z]){2})(?![\d-]*([A-Za-z])(?:[\d-]*\1) [\d-]*$)[A-Za-z\d-]{6,40}$

See the regex demo. If you use it in C# or PHP, consider replacing ^ with \A and $ with \z to make sure you match the entire string even in case there is a trailing newline.

Details:

  • ^ - start of string
  • (?!\d $) - fail the match if the string only consists of digits
  • (?!- $) - fail the match if the string only consists of hyphens
  • (?=(?:[\d-]*[A-Za-z]){2}) - there must be at least two ASCII letters after any zero or more digits or hyphens
  • (?![\d-]*([A-Za-z])(?:[\d-]*\1) [\d-]*$) - fail the match if the string contains two or more identical letters (the after (?:[\d-]*\1) means there can be any one letter)
  • [A-Za-z\d-]{6,40} - six to forty alphanumeric or hyphen chars
  • $ - end of string. (\z might be preferable.)

CodePudding user response:

Rule 1 eliminates rule 4 and 5: It can neither contain only hyphens, nor only digits.

/^(?=[a-z\d-]{6,40}$)[\d-]*([a-z]).*?(?!\1)[a-z].*$/i
  • (?=[a-z\d-]{6,40}$) look ahead for specified characters from 6 to 40
  • ([a-z]).*?(?!\1)[a-z] checks for two letters and at least one different

See this demo at regex101

This pattern with i flag considers A and a as the "same" letter (caseless matching) and will require another alpbhabet. For case sensitive matching here another demo at regex101.

  • Related