Generate Random Password based on Regex Pattern

Jassim Al Rahma 1,616 Reputation points
2021-06-27T20:53:09.697+00:00

Hi,

I have below Regex for my password:

internal const string PasswordRegex = @"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{8,15}$";

How can i generate random passwords which match the above pattern?

Thanks,
Jassim

Developer technologies .NET Xamarin
Developer technologies C#
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2021-06-28T00:06:06.18+00:00

    If not opposed to a non regular expression generator, see the following NuGet package, source code, test. The package has over 500.000 downloads and meets OWASP requirements.

    0 comments No comments

  2. Wenyan Zhang (Shanghai Wicresoft Co,.Ltd.) 36,436 Reputation points Microsoft External Staff
    2021-06-28T09:57:18.367+00:00

    Hello,
    Welcome to our Microsoft Q&A platform!
    You can get the random passwords like following code:

    string chars = "0123456789ABCDEFGHIJKLMNOPQSTUVWXYZabcdefghijklmnpqrstuvwxyz";  
    private string creat()  
    {  
    Random randomNnmber = new Random();  
    int len = randomNnmber.Next(8, 15);//get the max(15) and min(8)  
    string randomStr = "";  
      
    for (int i = 0; i < len; i++)  
    {  
    randomStr += chars[randomNnmber.Next(chars.Length)];  
    }  
    if (!Regex.IsMatch(randomStr, PasswordRegex))// the PasswordRegex you provided  
    {  
    Console.WriteLine($"{randomStr}");  
    return creat();  
    }  
    else  
    {  
    Console.WriteLine($"{randomStr}");  
    return randomStr;  
    }  
    }  
    

    Best Regards,

    Wenyan Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.