C# 检查密码是否为“8个字符,包括1个大写字母、1个特殊字符、字母数字字符”的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9477906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regular expression to check if password is "8 characters including 1 uppercase letter, 1 special character, alphanumeric characters"
提问by Rania Umair
I want a regular expression to check that
我想要一个正则表达式来检查
a password must be eight characters including one uppercase letter, one special character and alphanumeric characters.
密码必须为八个字符,包括一个大写字母、一个特殊字符和字母数字字符。
And here is my validation expression which is for eight characters including one uppercase letter, one lowercase letter, and one number or special character.
这是我的验证表达式,它适用于八个字符,包括一个大写字母、一个小写字母和一个数字或特殊字符。
(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$"
How I can write it for a password that must be eight characters including one uppercase letter, one special character and alphanumeric characters?
对于必须为八个字符(包括一个大写字母、一个特殊字符和字母数字字符)的密码,我该如何编写它?
采纳答案by npinti
The regular expression you are after will most likely be huge and a nightmare to maintain especially for people who are not that familiar with regular expressions.
您所追求的正则表达式很可能是巨大的,并且是维护的噩梦,尤其是对于那些不熟悉正则表达式的人。
I think it would be easier to break your regex down and do it one bit at a time. It might take a bit more to do, but I am pretty sure that maintaining it and debugging it would be easier. This would also allow you to provide more directed error messages to your users (other than just Invalid Password) which should improve user experience.
我认为分解正则表达式并一次做一点会更容易。可能需要做更多的工作,但我很确定维护和调试它会更容易。这也将允许您向您的用户提供更多定向错误消息(不仅仅是Invalid Password),这应该会改善用户体验。
From what I am seeing you are pretty fluent in regex, so I would presume that giving you the regular expressions to do what you need would be futile.
从我所看到的,你对正则表达式非常流利,所以我认为给你正则表达式来做你需要的事情是徒劳的。
Seeing your comment, this is how I would go about it:
看到你的评论,我是这样处理的:
Must be eight characters Long: You do not need a regex for this. Using the
.Lengthproperty should be enough.Including one uppercase letter: You can use the
[A-Z]+regular expression. If the string contains at least one upper case letter, this regular expression will yieldtrue.One special character: You can use either the
\Wwhich will match any character which is not a letter or a number or else, you can use something like so[!@#]to specify a custom list of special characters. Note though that characters such as$,^,(and)are special characters in the regular expression language, so they need to be escaped like so:\$. So in short, you might use the\W.Alphanumeric characters: Using the
\w+should match any letter and number and underscore.
必须是八个字符长:您不需要为此使用正则表达式。使用该
.Length属性应该就足够了。包括一个大写字母:可以使用
[A-Z]+正则表达式。如果字符串包含至少一个大写字母,则此正则表达式将产生true.一个特殊字符:您可以使用
\W将匹配任何不是字母或数字的字符的 ,或者您可以使用类似的东西[!@#]来指定特殊字符的自定义列表。不过,请注意字符如$,^,(和)是在正则表达式语言的特殊字符,所以需要进行转义像这样:\$。简而言之,您可以使用\W.字母数字字符:使用
\w+应该匹配任何字母、数字和下划线。
Take a look at thistutorial for more information.
查看本教程以获取更多信息。
回答by user1096188
If you need only one upper case and special character then this should work:
如果您只需要一个大写和特殊字符,那么这应该可以工作:
@"^(?=.{8,}$)(?=[^A-Z]*[A-Z][^A-Z]*$)\w*\W\w*$"
回答by mmdemirbas
( # Start of group
(?=.*\d) # must contain at least one digit
(?=.*[A-Z]) # must contain at least one uppercase character
(?=.*\W) # must contain at least one special symbol
. # match anything with previous condition checking
{8,8} # length is exactly 8 characters
) # End of group
In one line:
在一行中:
((?=.*\d)(?=.*[A-Z])(?=.*\W).{8,8})
Edit 2019-05-28:
编辑 2019-05-28:
You need to match entire input string. So, you can enclose the regex between ^and $to prevent accidentally assuming partial matches as matching entire input:
您需要匹配整个输入字符串。因此,您可以将正则表达式包含在^和之间,$以防止意外假设部分匹配与整个输入匹配:
^((?=.*\d)(?=.*[A-Z])(?=.*\W).{8,8})$
Sources:
资料来源:
回答by stema
As an example how this could be done with a readable/maintainable regex.
例如,如何使用可读/可维护的正则表达式完成此操作。
For a longer regex you should always use RegexOptions.IgnorePatternWhitespaceto allow whitespace and comments in the expression for better readability.
对于较长的正则表达式,您应该始终使用RegexOptions.IgnorePatternWhitespace允许表达式中的空格和注释以获得更好的可读性。
String[] passwords = { "foobar", "Foobar", "Foobar1", "Fooobar12" };
foreach (String s in passwords) {
Match password = Regex.Match(s, @"
^ # Match the start of the string
(?=.*\p{Lu}) # Positive lookahead assertion, is true when there is an uppercase letter
(?=.*\P{L}) # Positive lookahead assertion, is true when there is a non-letter
\S{8,} # At least 8 non whitespace characters
$ # Match the end of the string
", RegexOptions.IgnorePatternWhitespace);
if (password.Success) {
Console.WriteLine(s + ": valid");
}
else {
Console.WriteLine(s + ": invalid");
}
}
Console.ReadLine();
回答by Kailash Karki
/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/
回答by Preston L. Bannister
The answer is to not use a regular expression. This is sets and counting.
答案是不要使用正则表达式。这是设置和计数。
Regular expressions are about order.
正则表达式是关于顺序的。
In your life as a programmer you will asked to do many things that do not make sense. Learn to dig a level deeper. Learn when the question is wrong.
在您作为程序员的生活中,您会要求做许多没有意义的事情。学习深入挖掘一个层次。当问题错了时学习。
The question (if it mentioned regular expressions) is wrong.
问题(如果它提到正则表达式)是错误的。
Pseudocode (been switching between too many languages, of late):
伪代码(最近在太多语言之间切换):
if s.length < 8:
return False
nUpper = nLower = nAlphanum = nSpecial = 0
for c in s:
if isUpper(c):
nUpper++
if isLower(c):
nLower++
if isAlphanumeric(c):
nAlphanum++
if isSpecial(c):
nSpecial++
return (0 < nUpper) and (0 < nAlphanum) and (0 < nSpecial)
Bet you read and understood the above code almost instantly. Bet you took much longer with the regex, and are less certain it is correct. Extending the regex is risky. Extended the immediate above, much less so.
打赌您几乎立即阅读并理解了上述代码。打赌您使用正则表达式的时间要长得多,并且不太确定它是正确的。扩展正则表达式是有风险的。扩展上面的直接,更不用说。
Note also the question is imprecisely phrased. Is the character set ASCII or Unicode, or ?? My guess from reading the question is that at least one lowercase character is assumed. So I think the assumed last rule should be:
另请注意,该问题的措辞不准确。字符集是ASCII还是Unicode,还是?? 我从阅读问题的猜测是假设至少有一个小写字符。所以我认为假设的最后一条规则应该是:
return (0 < nUpper) and (0 < nLower) and (0 < nAlphanum) and (0 < nSpecial)
(Changing hats to security-focused, this is a reallyannoying/not useful rule.)
(将帽子更改为以安全为中心,这是一个非常烦人/无用的规则。)
Learning to know when the question is wrong is massively more important than clever answers. A clever answer to the wrong question is almost always wrong.
学会知道什么时候问题错了比聪明的答案重要得多。对错误问题的巧妙回答几乎总是错误的。
回答by Bakudan
This question starts to be viral and a lot of interesting suggestion appeared.
这个问题开始流行,出现了很多有趣的建议。
Yes, writing by hand is difficult. So an easier solution is to use a template. Although the resulted regex may not be most optimal, it will be easier to maintain and/or change, and the user will have a better control over the result. It is possible that I missed something, so any constructive criticism will be helpful.
是的,手写很难。因此,更简单的解决方案是使用模板。尽管生成的正则表达式可能不是最佳的,但它会更容易维护和/或更改,并且用户可以更好地控制结果。我可能漏掉了一些东西,所以任何建设性的批评都会有所帮助。
This links might be interesting: match at least 2 digits 2 letters in any order in a string, Regular Expression Language, Capturing groups
这个链接可能很有趣:在字符串、正则表达式语言、捕获组中以任意顺序匹配至少 2 个数字 2 个字母
I'm using this template (?=(?:.*?({type})){({count})})based on all of the regex I saw in SO. The next step is replacing the needed pattern ( number, special character... ) and adding configuration for length.
我正在使用(?=(?:.*?({type})){({count})})基于我在 SO 中看到的所有正则表达式的模板。下一步是替换所需的模式 ( number, special character... ) 并添加长度配置。
I've made a little class for composing the regex PasswordRegexGenerator.csAn example:
我编写了一个小类来编写正则表达式PasswordRegexGenerator.cs一个例子:
string result = new PasswordRegexGenerator ( )
.UpperCase ( 3, -1 ) // ... {3,}
.Number ( 2, 4 ) // ... {2,4}
.SpecialCharacter ( 2 ) // ... {2}
.Total ( 8,-1 )
.Compose ( );
/// <summary>
/// Generator for regular expression, validating password requirements.
/// </summary>
public class PasswordRegexGenerator
{
private string _elementTemplate = "(?=(?:.*?({type})){({count})})";
private Dictionary<string, string> _elements = new Dictionary<string, string> {
{ "uppercase", "[A-Z]" },
{ "lowercase", "[a-z]" },
{ "number", @"\d" },
{ "special", @"\W" },
{ "alphanumeric", @"\w" }
};
private StringBuilder _sb = new StringBuilder ( );
private string Construct ( string what, int min, int max )
{
StringBuilder sb = new StringBuilder ( _elementTemplate );
string count = min.ToString ( );
if ( max == -1 )
{
count += ",";
}
else if ( max > 0 )
{
count += "," + max.ToString();
}
return sb
.Replace ( "({type})", what )
.Replace ( "({count})", count )
.ToString ( );
}
/// <summary>
/// Change the template for the generation of the regex parts
/// </summary>
/// <param name="newTemplate">the new template</param>
/// <returns></returns>
public PasswordRegexGenerator ChangeRegexTemplate ( string newTemplate )
{
_elementTemplate = newTemplate;
return this;
}
/// <summary>
/// Change or update the regex for a certain type ( number, uppercase ... )
/// </summary>
/// <param name="name">type of the regex</param>
/// <param name="regex">new value for the regex</param>
/// <returns></returns>
public PasswordRegexGenerator ChangeRegexElements ( string name, string regex )
{
if ( _elements.ContainsKey ( name ) )
{
_elements[ name ] = regex;
}
else
{
_elements.Add ( name, regex );
}
return this;
}
#region construction methods
/// <summary>
/// Adding number requirement
/// </summary>
/// <param name="min"></param>
/// <param name="max"></param>
/// <returns></returns>
public PasswordRegexGenerator Number ( int min = 1, int max = 0 )
{
_sb.Append ( Construct ( _elements[ "number" ], min, max ) );
return this;
}
public PasswordRegexGenerator UpperCase ( int min = 1, int max = 0 )
{
_sb.Append ( Construct ( _elements[ "uppercase" ], min, max ) );
return this;
}
public PasswordRegexGenerator LowerCase ( int min = 1, int max = 0 )
{
_sb.Append ( Construct ( _elements[ "lowercase" ], min, max ) );
return this;
}
public PasswordRegexGenerator SpecialCharacter ( int min = 1, int max = 0 )
{
_sb.Append ( Construct ( _elements[ "special" ], min, max ) );
return this;
}
public PasswordRegexGenerator Total ( int min, int max = 0 )
{
string count = min.ToString ( ) + ( ( max == 0 ) ? "" : "," + max.ToString ( ) );
_sb.Append ( ".{" + count + "}" );
return this;
}
#endregion
public string Compose ()
{
return "(" + _sb.ToString ( ) + ")";
}
}
回答by Matt Timmermans
So many answers.... all bad!
这么多答案......都不好!
Regular expressions don't have an AND operator, so it's pretty hard to write a regex that matches valid passwords, when validity is defined by something AND something else AND something else...
正则表达式没有 AND 运算符,因此当有效性由某些东西和其他东西以及其他东西定义时,很难编写匹配有效密码的正则表达式......
But, regular expressions dohave an OR operator, so just apply DeMorgan's theorem, and write a regex that matches invalidpasswords.
但是,正则表达式确实有一个 OR 运算符,因此只需应用 DeMorgan 定理,并编写一个匹配无效密码的正则表达式。
anything with less than 8 characters ORanything with no numbers ORanything with no uppercase ORanything with no special characters
任何少于 8 个字符的任何内容或任何没有数字的内容或任何没有大写的内容或任何没有特殊字符的内容
So:
所以:
^(.{0,7}|[^0-9]*|[^A-Z]*|[a-zA-Z0-9]*)$
If anything matches that, then it's an invalidpassword.
如果有任何匹配,那么它是一个无效的密码。
回答by Lucas Silva
The regular expression you was looking for is: /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*\[\]"\';:_\-<>\., =\+\/\\]).{8,}$/u.
您要查找的正则表达式是:/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*\[\]"\';:_\-<>\., =\+\/\\]).{8,}$/u。
Example and test: http://regexr.com/3fhr4
示例和测试:http: //regexr.com/3fhr4
回答by amit pandya
You can use below class for validation:
您可以使用以下类进行验证:
public class PasswordValidator{
private Pattern pattern;
private Matcher matcher;
private static final String PASSWORD_PATTERN =
"((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})";
public PasswordValidator(){
pattern = Pattern.compile(PASSWORD_PATTERN);
}
/**
* Validate password with regular expression
* @param password password for validation
* @return true valid password, false invalid password
*/
public boolean validate(final String password){
matcher = pattern.matcher(password);
return matcher.matches();
}
}
where 6 and 20 are minimum and maximum length for the password.
其中 6 和 20 是密码的最小和最大长度。

