Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
576 views
in Technique[技术] by (71.8m points)

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

I need a regex that tests a string for a

  • minimum of 14 characters - valid are A-Za-z0-9#,.-_
  • minimum of 6 letters within that 14
  • minimum of 2 numbers within that 14

Is there a way I can wrap this up in one regular expression (currently I have a javascript and php function that does three separate tests, one that it is 14 total, another that there is at least two numbers, and another that there is at least 6 letters.

So the following would be valid:

  • blabla2bla2f54a (valid >14 total, with at least 6 letters, at least 2 numbers)
  • thisIsNotValidAtAll (invalid because less than 2 numbers)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...