首页 > 解决方案 > 至少一个大写、一个小写、一个数字和一个特殊字符的正则表达式

问题描述

我正在编写一个 android 正则表达式来检查包含的密码,我使用的正则表达式是

^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W_]).{8,16}$

但我的 Matcher 类总是返回 false

     Matcher matcher;

        Pattern pattern = Pattern.compile(context.getString(R.string.password_validation_value));

matcher = pattern.matcher(password); // always returns false

我该如何解决这个问题?

标签: regexregex-lookaroundsregex-groupregex-greedy

解决方案


好的,这里有一个解释

^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\p{P}).{6,16}$

解释

 ^                     # Beginning of string
 (?= .* \d )           # Assert, string contains a digit
 (?= .* [a-z] )        # Assert, string contains a lower case letter
 (?= .* [A-Z] )        # Assert, string contains a upper case letter
 (?= .* \p{P} )        # Assert, string contains a punctuation character
 .{6,16}               # Consume 6 to 16 characters
 $                     # End of string

推荐阅读