Wesley Raeel
Wesley Raeel

Reputation: 41

Regex without special characters

I am using regex for validate password

this is my regex configuration

@"^(?!.*[\s])(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{6,32}$"

My criteria is

Tests I was waiting for:

My code to check for errors:

using System;
using System.Text.RegularExpressions;

class Program
{

   static void Main(string[] args)
   {

      var totalTestCases = int.Parse(Console.ReadLine());

      string S = "";
      string pattern = @"^(?!.*[\s])(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{6,32}$";

      var n = 0;
      do
      {
         n++;
         S = Console.ReadLine();
         if (S != "")
         {
            // Console.WriteLine("{0}", Regex.IsMatch(S, pattern) ? "Senha valida." : "Senha invalida.");
            string test = Regex.IsMatch(S, pattern) ? "Password valid." : "Password invalid.";
            Console.WriteLine(test);
         }
      } while (n < totalTestCases);
   }
}

Upvotes: 2

Views: 1228

Answers (2)

Palle Due
Palle Due

Reputation: 6292

@Arpit Patel's answer is perfectly fine, but I'll just take a minute to explain what's wrong with your approach. Let's break it up:

  • ^(?!.*[\s]): Negative look ahead says "No whitespace". That's fine.
  • (?=.*[0-9]): Positive look ahead says: "There must be a number". That's fine.
  • (?=.*[a-z]): Positive look ahead says: "There must be a lowercase letter". That's fine.
  • (?=.*[A-Z]): Positive look ahead says: "There must be an uppercase letter". That's fine.
  • .: Anything goes! That's obviously wrong.
  • {6,32}: Length requirement.

So Arpit's answer:

^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{6,32}$

does away with the "anything goes" and inserts the legal characters instead. Thereby the negative look ahead is no longer needed since whitespace is prohibited.

Upvotes: 1

user11469175
user11469175

Reputation:

Try to put this Regex in your code it will work for your conditions.

/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{6,32}$/

Replace pattern variable with below code :)

string pattern = @"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{6,32}$";

Upvotes: 1

Related Questions