正则表达式密码 [英] regex for password

查看:228
本文介绍了正则表达式密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将密码的最低要求的正则表达式设置为最少6个字符; 1个大写,1个小写和1个数字。看起来很简单?我没有任何关于正面向上前瞻的经验,所以我会这样做:

I'm trying to get regex for minimum requirements of a password to be minimum of 6 characters; 1 uppercase, 1 lowercase, and 1 number. Seems easy enough? I have not had any experience in regex's that "look ahead", so I would just do:

if(!pwStr.match(/[A-Z]+/) || !pwStr.match(/[a-z]+/) || !pwStr.match(/[0-9]+/) ||
    pwStr.length < 6)
    //was not successful

但我想将其优化为一个正则表达式并且在此过程中升级我的正则表达式技能。

But I'd like to optimize this to one regex and level up my regex skillz in the process.

推荐答案

假设密码可能包含任何字符,则最小长度为至少六个字符,必须包含至少一个大写字母和一个小写字母和一个十进制数字,这是我推荐的那个:(使用python语法注释版本)

Assuming that a password may consist of any characters, have a minimum length of at least six characters and must contain at least one upper case letter and one lower case letter and one decimal digit, here's the one I'd recommend: (commented version using python syntax)

re_pwd_valid = re.compile("""
    # Validate password 6 char min with one upper, lower and number.
    ^                 # Anchor to start of string.
    (?=[^A-Z]*[A-Z])  # Assert at least one upper case letter.
    (?=[^a-z]*[a-z])  # Assert at least one lower case letter.
    (?=[^0-9]*[0-9])  # Assert at least one decimal digit.
    .{6,}             # Match password with at least 6 chars
    $                 # Anchor to end of string.
    """, re.VERBOSE)

这里是JavaScript:

Here it is in JavaScript:

re_pwd_valid = /^(?=[^A-Z]*[A-Z])(?=[^a-z]*[a-z])(?=[^0-9]*[0-9]).{6,}$/;

附加:如果您需要多个必需的字符,请查看我的回答类似的密码验证问题

Additional: If you ever need to require more than one of the required chars, take a look at my answer to a similar password validation question

编辑:将懒角星更改为贪婪的char类。感谢Erik Reppen - 不错优化!

Changed the lazy dot star to greedy char classes. Thanks Erik Reppen - nice optimization!

这篇关于正则表达式密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆