开发者

Weak password of 6 characters or more with at least 1 digit

开发者 https://www.devze.com 2023-03-27 23:18 出处:网络
I want to create regular expression for password that has length of atleast 6 characters and contains at least 1 digit in it. This is the expression I came up with:

I want to create regular expression for password that has length of atleast 6 characters and contains at least 1 digit in it. This is the expression I came up with:

Regex regEx = new Regex(@"^?=\d.{6,}$");

But this doesn't seem to work. Can anybody tell me why?

I guess it says between beginning and ending, it performs look ahead to see if any digit appears in password. It appears, then says anything can repeat {6,} says minimum 6 characters. But this doesn't seem to work. Can anybody correct me on this?

Update: On requ开发者_JS百科est of Albin Sunnanbo I have changed title from strong password to weak.


Regular expressions are not very good at requirements like "contains at least x at any position".

Try this:

bool result = (password.Length >= 6) && password.Any(char.IsDigit);


Your noncapturing group is missing parenthesis. Try this:

^(?=.*\d).{6,}$

Small test to verify some basic functionality:

    [TestMethod]
    public void CheckAtLeastNotSuperWeakPassword()
    {
        var r = new Regex(@"^(?=.*\d).{6,}$");
        Action<string, bool> a = (s, b) =>
        {
            Assert.AreEqual(b, r.IsMatch(s), s);
        };
        a("", false);
        a("a", false);
        a("abcdef", false);
        a("abcdefg", false);
        a("1", false);
        a("abc1e", false);
        a("abc1ef", true);
        a("1bcaef", true);
        a("cbcae1", true);
        a("cbcae1wqd32", true);
    }


Password Validation via RegEx has a decent discussion about the topic.

You can use:

^\w*(?=\w*\d)(?=\w*.{6,})\w*$


I don't see this as a problem for regular expressions. If you have a set of criteria for a password string, just write code to check for those.

You'll end up with a much more expresive, easier to maintain solution in the long run.

pseudocode-ish

 If pass <> confirmPass Then
        FailPasswordCheck("Password and confirmation did not match.")
        Return False
    End If
    If pass.Length < 7 Then
        FailPasswordCheck("Password must be at least 7 characters long.")
        Return False
    End If

    If Not ContaintsNumericChar(pass) Then
        FailPasswordCheck("Password must have at least 1 number.")
        Return False
    End If


Here's a nice simple one:

(?=.*/d).{6}

Explained

(?=.*/d)       #a look around for a digit preceded by any number of chars.
.{6}           #6 chars

Note: I don't include the start (^), end of string ($), or more than 6 chars ({6,}) because they aren't strictly necessary for the original question.

0

精彩评论

暂无评论...
验证码 换一张
取 消