1

Why regex on regex101.com is not quite identical in C# code? for example I want to validate a password which must contains:

  • At least one upper case
  • At least one lower case
  • At least one number
  • At least one special character
  • At least length should be 8 characters or greater

The regex that I use is: ((?=.*\d)(?=.*[A-Z])(?=.*\W).{8,50000})

And it works on website.

Here is the example

However, when I transfer it to C# code, when I entered correct value such as for example Testable.345 it shows an validation message (it doesnt pass). Here is the code in my C#:

 class Program
    {
        static void Main(string[] args)
        {

            string input = Startup();
            GetMatched(input);
        }

        private static string Startup()
        {
            Console.WriteLine("Please enter string for regex match: ");
            string input = Console.ReadLine();
            return input;
        }

        private static void GetMatched(string input)
        {
            if (!string.IsNullOrWhiteSpace(input))
            {
                const string digitsRegex = "((?=.*\\d)(?=.*[A - Z])(?=.*\\W).{ 8,50000})";

                Regex regex = new Regex(digitsRegex, RegexOptions.CultureInvariant);
                string fieldData = input.ToString().Replace(" ", "");


                if (regex.IsMatch(fieldData))
                {
                    Console.WriteLine("Success!");
                    Console.ReadLine();
                }
                else
                {
                    Console.WriteLine("Failed!");
                    Console.ReadLine();
                    Startup();
                }
            }
        }
    }
Stefan89BEG
  • 129
  • 2
  • 4
  • 17

1 Answers1

2

/** Requirements: (Must contain at least one of each condition ): a lowercase alpha character, a uppercase alpha character, a numeric character, a nonalphanumeric character, minimum string length is 8 **/

(?=^.[a-z]{1}.$)(?=^.[A-Z]{1}.$)(?=^.[0-9]{1}.$)(?=^.[^0-9a-zA-Z]{1}.$)(?=.{8})