C# 字母数字密码的正则表达式,至少包含 1 个数字和字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1195665/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 10:34:05  来源:igfitidea点击:

Regex for alphanumeric password, with at least 1 number and character

c#javascript

提问by mrblah

Need help with a regex for alphanumeric password, with at least 1 number and character, and the length must be between 8-20 characters.

需要关于字母数字密码的正则表达式的帮助,至少有 1 个数字和字符,长度必须在 8-20 个字符之间。

I have this but doesn't seem to be working (it doesn't have length requirements either):

我有这个,但似乎没有用(它也没有长度要求):

^[A-Za-z0-9]*[A-Za-z][A-Za-z0-9]*$

回答by cwap

^(?=.{8,20}$)(?=.*[0-9])(?=.*[a-zA-Z]).*

? :)

? :)

回答by Sanjay Sheth

Wouldn't it be better to do this validation with some simple string functions instead of trying to shoehorn a difficult to validate regex into doing this?

用一些简单的字符串函数来做这个验证,而不是试图用一个难以验证的正则表达式来做这个,不是更好吗?

回答by Adam Robinson

If you take a look at this MSDN link, it gives an example of a password validation RegEx expression, and (more specifically) how to use it in ASP.NET.

如果您查看此MSDN 链接,它提供了密码验证 RegEx 表达式的示例,以及(更具体地说)如何在 ASP.NET 中使用它。

For what you're looking to accomplish, this should work:

对于您要完成的工作,这应该有效:

    (?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,20})$

This requires at least one digit, at least one alphabetic character, no special characters, and from 8-20 characters in length.

这需要至少一位数字,至少一个字母字符,没有特殊字符,并且长度为 8-20 个字符。

回答by John Fisher

Something like this will be closer to your needs. (I didn't test it, though.)

这样的事情将更接近您的需求。(不过,我没有测试它。)

Regex test = new Regex("^(?:(?<ch>[A-Za-z])|(?<num>[9-0])){8,20}$");
Match m = test.Match(input);
if (m.Success && m.Groups["ch"].Captures.Count > 1 && m.Groups["num"].Captures.Count > 1)
{
  // It's a good password.
}

回答by S Pangborn

Why not just use a handful of simple functions to check?

为什么不使用一些简单的函数来检查呢?

checkPasswordLength( String password);
checkPasswordNumber( String password);

Maybe a few more to check for occurrences of the same character repeatedly and consecutively.

也许还有几个来重复和连续检查相同字符的出现。

回答by Raj kumar pandey

This code is for javascript

此代码用于 javascript

// *********** ALPHA-Numeric check ***************************
function checkAlphaNumeric(val)
{
    var mystring=new String(val)

    if(mystring.search(/[0-9]+/)==-1) // Check at-leat one number
    {
        return false;
    }
    if(mystring.search(/[A-Z]+/)==-1 && mystring.search(/[a-z]+/)==-1) // Check at-leat one character
    {
        return false;
    }
}