Dmitry Makovetskiyd
Dmitry Makovetskiyd

Reputation: 7053

Regular expression help

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

Answers (4)

Victor Hurdugaci
Victor Hurdugaci

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

Till
Till

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

Rajeev
Rajeev

Reputation: 4839

This checks for a digit in password string

^(?=.*\d+)[\w]{8,}$

Upvotes: 1

Paul Creasey
Paul Creasey

Reputation: 28834

I suggest you use 2 regex validations:

\d

and

.{8,}

much more understandable.

Upvotes: 2

Related Questions