Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for no more than two repeated letters/digits

Tags:

I have a requirement to handle a regular expression for no more than two of the same letters/digits in an XSL file.

  • no space
  • does not support special chars
  • support (a-z,A-Z,0-9)
  • require one of a-z
  • require one of 0-9
  • no more than 2 same letter/digits (i.e., BBB will fail, BB is accepted)

What I have so far

(?:[^a-zA-Z0-9]{1,2}) 
like image 263
cool_spirit Avatar asked Jul 31 '13 14:07

cool_spirit


People also ask

What is '?' In regular expression?

'?' matches/verifies the zero or single occurrence of the group preceding it. Check Mobile number example. Same goes with '*' . It will check zero or more occurrences of group preceding it.

Which character will be used for zero or more occurrences in regular expression?

A regular expression followed by an asterisk ( * ) matches zero or more occurrences of the regular expression.

How do you repeat a regular expression?

A repeat is an expression that is repeated an arbitrary number of times. An expression followed by '*' can be repeated any number of times, including zero. An expression followed by '+' can be repeated any number of times, but at least once.


2 Answers

This regex will do it: ^(?!.*([A-Za-z0-9])\1{2})(?=.*[a-z])(?=.*\d)[A-Za-z0-9]+$

Here's the breakdown:

(?!.*([A-Za-z0-9])\1{2}) makes sure that none of the chars repeat more than twice in a row.

(?=.*[a-z]) requires at least one lowercase letter

(?=.*\d) requires at least one digit

[A-Za-z0-9]+ allows only letters and digits

EDIT : removed an extraneous .* from the negative lookahead

like image 174
Brian Stephens Avatar answered Sep 20 '22 13:09

Brian Stephens


(Partial solution) For matching the same character repeated 3 or more times consecutively, try:

([a-zA-Z0-9])\1{2,} 

Sample matches (tested both here and here): AABBAA (no matches), AABBBAAA (matches BBB and AAA), ABABABABABABABA (no matches), ABCCCCCCCCCC (matches CCCCCCCCCC).

like image 44
Racso Avatar answered Sep 19 '22 13:09

Racso