Reputation: 7053
I need a regular expression that requires a password to have at least 8 characters and a number.
Also, is there a website that allows me to generate regular expressions automatically?
Upvotes: 0
Views: 98
Reputation: 28425
If characters in "8 characters and a number" means "non-digit characters" then I wouldn't use a regex to validate this. Is too complicated to do it with one regex.
Is easier just to check each character and increment two variables (one of non digit chars'c' and one for digits 'd') and check the values in the end:
d >=1 && c >=1 && d+c >= 8 <- good password
Later edit: I just saw the solution with regex lookahead. While that one works I still believe that this problem can be solved with only one traversal, with no lookahead
Upvotes: 0
Reputation: 3154
using System;
using System.Text;
using System.Text.RegularExpressions;
namespace TestConsoleAppCSharp
{
class Program
{
static void Main(string[] args)
{
string[] passwords = {"test123", "testtest", "testtest123"};
foreach (string pw in passwords)
{
Console.WriteLine(Regex.IsMatch(pw, @"^.*(?=.{8,})(?=.*\d)") ? String.Format("{0}: Yepp", pw) : String.Format("{0}: Nope", pw));
}
}
}
}
Upvotes: 1
Reputation: 28834
I suggest you use 2 regex validations:
\d
and
.{8,}
much more understandable.
Upvotes: 2