在Google和SO上广泛搜索后,我遇到了一个问题。我试图写一个基于我在SO
上找到的正则表达式字符串必须为8-24个字符,
除了长度之外,字符串还需要符合以下两个条件(最低限度):
这是我一直试图修改的正则表达式:
^.*(?=.{8,24})(?=.*\d|\W)(?=.*[a-zA-Z]).*$
我需要修改这是为了确保密码符合上述条件。
我无法进入并以编程方式执行此操作,因为它会改变我们的一些代码如何工作的其他基础知识。现在我们正在进行正则表达式检查,所以我必须做的就是使用新表达式更新配置文件。
答案 0 :(得分:2)
也许尝试类似(删除空格)
^
(((?=.*[a-z])
((?=.*[A-Z])|(?=.*\d)|(?=.*\W))) |
((?=.*[A-Z])
((?=.*\d)|(?=.*\W))) |
((?=.*\d)(?=.*\W)))
.{8,24}
$
结构如下:
^<char restrictions><length restriction>$
,其中
char restriction = (<lower> and (<upper> or <numeric> or <non-alphanum>))
or (<upper> and (<numeric> or <non-alphanum>))
or (<numeric> and <non-alphanum>)
(所有这些都是前瞻性的。)
长度限制不是前瞻,因为我们需要告诉正则表达式引擎在字符串的开头和结尾之间应该有8到24个字符。 (通过将.*
置于顶层,我们将失去执行此限制的能力。)
然而,人们应该尽一切努力改变代码,而不是使用这个可怕的正则表达式。
答案 1 :(得分:1)
不,它不漂亮,但你可以使用强力执行单一的正则表达式(假设是C#):
Regex re = new Regex(@"
# Match 2 of 4 passwords criteria and length from 8 to 24.
^ # Anchor to start of string.
(?: # Group acceptable pair alternatives.
(?=[^A-Z]*[A-Z]) # At least one Upper Case.
(?=[^a-z]*[a-z]) # At least one Lower Case.
| # or...
(?=[^A-Z]*[A-Z]) # At least one Upper Case.
(?=[^0-9]*[0-9]) # At least one Numeric.
| # or...
(?=[^A-Z]*[A-Z]) # At least one Upper Case.
(?=\w*\W) # At least one Non-AlphaNumeric.
| # or...
(?=[^a-z]*[a-z]) # At least one Lower Case.
(?=[^0-9]*[0-9]) # At least one Numeric.
| # or...
(?=[^a-z]*[a-z]) # At least one Lower Case.
(?=\w*\W) # At least one Non-AlphaNumeric.
| # or...
(?=[^0-9]*[0-9]) # At least one Numeric.
(?=\w*\W) # At least one Non-AlphaNumeric.
) # Brute force!
.{8,24} # Match from 8 to 24 chars.
\z # Anchor to end of string.
", RegexOptions.IgnorePatternWhitespace);
if (re.IsMatch(text)) {
// Password is valid.
} else {
// Password is NOT valid.
}
4个要求中有2个有六种可能的组合。最后的.{8,24}
长度检查假定除换行之外的任何字符都可以(您可能/应该想要修改它)。
编辑:我现在看到dbaupp的答案工作得很好(我给了我的upvote)。虽然我的表达式是找到一个大写字母:(?=[^A-Z]*[A-Z])
比(?=.*[A-Z])
更有效(对于其他前瞻也是如此)。另一方面,dbaupp的答案在分组方面更有效。
答案 2 :(得分:0)
def check_password_strength(x):
## Initialize the toggle flags to check 3 conditions - Capital Letter/Small Letter/Numeric Value
flag_capital_letter = 0
flag_small_letter = 0
flag_numerical_letter = 0
## Message strings that will be displayed to the user
strong_pass_msg = "Strong password"
weak_pass_msg = "Weak Password"
if len(x) >= 6 and len(x) <= 12 : ## Ensure the Length of Password between [6,12], both inclusive
if '#' in x or '$' in x or '@' in x : ## At least one Special Character Should be in password
for i in x: ## Loop for parsing the string to check for 3 remaining conditions
if i.islower():
flag_small_letter = 1
if i.isupper():
flag_capital_letter = 1
if i.isnumeric():
flag_numerical_letter = 1
## if all three conditions are fulfilled, all flags toggle to 1
if flag_numerical_letter == 1 and flag_capital_letter == 1 and flag_small_letter == 1:
return(strong_pass_msg)
else:
return(weak_pass_msg)
else:
return(weak_pass_msg)
else:
return(weak_pass_msg)
username = input("Enter your Username: ")
password = input("Enter Password: ")
check_password_strength(password)