Regexp Java用于密码验证 [英] Regexp Java for password validation

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

问题描述

我正在为密码验证创建一个regexp,以便在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.

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

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