C#: Regular Expression To Check If Password Is “8 Characters Including 1 Uppercase Letter, 1 Special Character, Alphanumeric Characters”

You can use the following regular expression in C# to check if a password meets the given criteria:


Explanation of the regular expression:

  • ^ asserts the start of the string.
  • (?=.*[A-Z]) checks if there is at least one uppercase letter.
  • (?=.*[\W_]) checks if there is at least one special character (non-alphanumeric character).
  • (?=.*[a-zA-Z0-9]) checks if there is at least one alphanumeric character.
  • .{8,} checks if the string has at least 8 characters.
  • $ asserts the end of the string.

Example usage:

using System;
using System.Text.RegularExpressions;

public class Program
    public static void Main()
        string password = "Abc123#@";
        string regexPattern = "^(?=.*[A-Z])(?=.*[\\W_])(?=.*[a-zA-Z0-9]).{8,}$";
        bool isValidPassword = Regex.IsMatch(password, regexPattern);
        Console.WriteLine("Is valid password? " + isValidPassword); // Output: True

In the example above, the password "Abc123#@", which contains 8 characters including 1 uppercase letter, 1 special character, and alphanumeric characters, will be considered valid.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!