Regular expression for a string that must contain minimum 14 characters, where at minimum 2 are numbers, and at minimum 6 are letters

Easy! First lets look at a commented version in PHP:

$re="/# Match 14+ char password with min 2 digits and 6 letters.
    ^                       # Anchor to start of string.
    (?=(?:.*?[A-Za-z]){6})  # minimum of 6 letters.
    (?=(?:.*?[0-9]){2})     # minimum of 2 numbers.
    [A-Za-z0-9#,.\-_]{14,}  # Match minimum of 14 characters.
    $                       # Anchor to end of string.
    /x";

Here is the JavaScript version:

var re = /^(?=(?:.*?[A-Za-z]){6})(?=(?:.*?[0-9]){2})[A-Za-z0-9#,.\-_]{14,}$/;

Addendum 2012-11-30

I noticed that this answer recently got an upvote. This uses a more outdated expression so I figured it was time to update it with a better one.

=== A more efficient expression ===

By getting rid of the “dot-star” altogether and greedily applying a more precise expression, (a negated char class), an even more efficient solution results:

$re="/# Match 14+ char password with min 2 digits and 6 letters.
    ^                              # Anchor to start of string.
    (?=(?:[^A-Za-z]*[A-Za-z]){6})  # minimum of 6 letters.
    (?=(?:[^0-9]*[0-9]){2})        # minimum of 2 numbers.
    [A-Za-z0-9#,.\-_]{14,}         # Match minimum of 14 characters.
    $                              # Anchor to end of string.
    /x";

Here is the new JavaScript version:

var re = /^(?=(?:[^A-Za-z]*[A-Za-z]){6})(?=(?:[^0-9]*[0-9]){2})[A-Za-z0-9#,.\-_]{14,}$/;

  • Edit 1: Added #,.-_ to list of valid chars.
  • Edit 2: Changed the greedy to lazy star.
  • Edit 2012-11-30: Added alternate version with the “lazy-dot-star” replaced with a more efficient greedy application of a more precise expression.

Leave a Comment