duananyantan04633 2017-04-29 16:09
浏览 31
已采纳

为密码检查构建一个正则表达式

Hi i have a password strength check in PHP. that looks like this:

    public static function validPass($candidate) {
    $r1 = '/[A-Z]/';  //1 upper
    $r2 = '/[a-z]/';  //2 lower
    $r3 = '/[!@#$%^&*()\-_=+{}:<.>]/';  //1 special char
    $r4 = '/[0-9]/';  //1 number

    //no space
    if (preg_match('/\s/',$candidate)) {
        return false;
    }

    if (preg_match_all($r1, $candidate, $o) < 1) {
        return false;
    }
    if (preg_match_all($r2, $candidate, $o) < 1) {
        return false;
    }
    if (preg_match_all($r3, $candidate, $o) < 1) {
        return false;
    }
    if (preg_match_all($r4, $candidate, $o) < 1) {
        return false;
    }
    return true;
}

so 1 capital, 1 lower, 1 number, 1 special char and no spaces allowed

now i am using a javascript validator for the frontend and the only custom feature i can add for password is to add a regex so i have to build this into a regex. I tried and I have so far:

^(?=.*[^a-zA-Z])(?=.*[a-z])(?=.*[A-Z])$

but i dont know how to approach this. What is the best way to perform these checks into a regex?

  • 写回答

1条回答 默认 最新

  • dongwen7187 2017-04-29 16:19
    关注

    Your ^(?=.*[^a-zA-Z])(?=.*[a-z])(?=.*[A-Z])$ pattern is an example of a regex that will never match because, with lookaheads, you require at least 1 non-letter, uppercase and lowercase letters, but the consuming pattern only matches an empty string.

    You may use a single regex like

    ^(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*()_=+{}:<.>-])(?=.*[0-9])\S*$
    

    If you need to set a minmum number of characters, replace the last * with a limiting quantifier, e.g. {8,} to require at least 8 chars.

    See the regex demo.

    Details:

    • ^ - start of string
    • (?=.*[A-Z]) - at least one uppercase
    • (?=.*[a-z]) - - at least one lowercase
    • (?=.*[!@#$%^&*()_=+{}:<.>-]) - at least one special char
    • (?=.*[0-9]) - at least one digit
    • \S* - 0 or more non-whitespace chars
    • $ - end of strings.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)