1

I'm looking for a regex pattern that can limits matches based on maximum occurrences.

For example, match an alphanumeric string between 6-12 characters in length, and contains minimum 2, but NOT MORE THAN 4, uppercase letters, regardless of each of their positions in the string.

I've tried this pattern, but it only matches if the uppercase letters are located next to each other.

^([A-Z]{2,4}).{8,12}$

Valid matches would be:

HamBurger (2 uppercase, Length = 9)
LeTtUce (3 uppercase, Length = 7)
TACOss (4 uppercase, Length = 6)

But invalid matches would be:

ABCDE1234 (too many uppercase letters)
aBcDeFgHiJ (too many uppercase letters)
ADBC (length too short)

Thanks in advance for any assistance.

mass6
  • 13
  • 2
  • You should give [Reference - Password Validation](https://stackoverflow.com/q/48345922/3600709) a good read. – ctwheels Jun 19 '19 at 13:59

1 Answers1

0

You may use a lookahead based solution like

^(?=(?:[^A-Z]*[A-Z]){2,4}[^A-Z]*$).{6,12}$

Or, to make it more streamlined, move the length check to the start (into the lookahead):

^(?=.{6,12}$)(?:[^A-Z]*[A-Z]){2,4}[^A-Z]*$

See the regex demo (or this one) and the Regulex graph:

enter image description here

Details

  • ^ - start of a string
  • (?=(?:[^A-Z]*[A-Z]){2,4}[^A-Z]*$) - a positive lookahead that requires two to four repetitions of 0+ chars other than uppercase letters followed with an uppercase letter and then any 0+ chars other than uppercase letters to the end of the string
  • .{6,12} - 6 to 12 chars
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563