用于密码验证的正则表达式 Java [英] Regexp Java for password validation

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

问题描述

我正在创建一个用于密码验证的正则表达式,以在 Java 应用程序中用作配置参数.

I'm creating a regexp for password validation to be used in a Java application as a configuration parameter.

正则表达式是:

^.*(?=.{8,})(?=..*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$

密码策略是:

  • 至少 8 个字符

  • At least 8 chars

至少包含一位数

包含至少一个低位字母字符和一个高位字母字符

Contains at least one lower alpha char and one upper alpha char

在一组特殊字符(@#%$^ 等)中至少包含一个字符

Contains at least one char within a set of special chars (@#%$^ etc.)

不包含空格、制表符等

我只缺少第 5 点.我无法让正则表达式检查空格、制表符、回车等.

I’m missing just point 5. I'm not able to have the regexp check for space, tab, carriage return, etc.

有人可以帮我吗?

推荐答案

试试这个:

^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\S+$).{8,}$

说明:

^                 # start-of-string
(?=.*[0-9])       # a digit must occur at least once
(?=.*[a-z])       # a lower case letter must occur at least once
(?=.*[A-Z])       # an upper case letter must occur at least once
(?=.*[@#$%^&+=])  # a special character must occur at least once
(?=\S+$)          # no whitespace allowed in the entire string
.{8,}             # anything, at least eight places though
$                 # end-of-string

添加、修改或删除单个规则很容易,因为每个规则都是一个独立的模块".

It's easy to add, modify or remove individual rules, since every rule is an independent "module".

(?=.*[xyz]) 构造吃掉整个字符串 (.*) 并回溯到 [xyz] 可以匹配.如果找到 [xyz] 则成功,否则失败.

The (?=.*[xyz]) construct eats the entire string (.*) and backtracks to the first occurrence where [xyz] can match. It succeeds if [xyz] is found, it fails otherwise.

另一种选择是使用不情愿的限定符:(?=.*?[xyz]).对于密码检查,这几乎没有任何区别,对于更长的字符串,它可能是更有效的变体.

The alternative would be using a reluctant qualifier: (?=.*?[xyz]). For a password check, this will hardly make any difference, for much longer strings it could be the more efficient variant.

最有效的变体(但最难阅读和维护,因此最容易出错)当然是 (?=[^xyz]*[xyz]).对于这种长度的正则表达式并为此目的,我不建议这样做,因为它没有真正的好处.

The most efficient variant (but hardest to read and maintain, therefore the most error-prone) would be (?=[^xyz]*[xyz]), of course. For a regex of this length and for this purpose, I would dis-recommend doing it that way, as it has no real benefits.

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

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