简体   繁体   English

没有特殊字符的正则表达式

[英]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我的标准是

  • The password must contain at least one uppercase letter, one lowercase letter and a number;密码必须至少包含一个大写字母、一个小写字母和一个数字;
  • It cannot have any special character, accent or space;它不能有任何特殊字符、重音或空格;
  • In addition, the password can be 6 to 32 characters long.此外,密码长度可以为 6 到 32 个字符。

Tests I was waiting for:我正在等待的测试:

  • BIT123456 Is Invalid BIT123456 无效
  • Year2021 Is Valid 2021年有效
  • Fing!2020 Is Invalid ( but it returns valid )

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);
   }
}

Try to put this Regex in your code it will work for your conditions.尝试将此 Regex 放入您的代码中,它将适用于您的条件。

/^(?=.*\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}$";

@Arpit Patel's answer is perfectly fine, but I'll just take a minute to explain what's wrong with your approach. @Arpit Patel 的回答非常好,但我会花一点时间来解释你的方法有什么问题。 Let's break it up:让我们分解一下:

  • ^(?.:*[\s]). ^(?.:*[\s])。 Negative look ahead says "No whitespace".负面展望表示“没有空格”。 That's fine.没关系。
  • (?=.*[0-9]): Positive look ahead says: "There must be a number". (?=.*[0-9]):正面展望说:“必须有一个数字”。 That's fine.没关系。
  • (?=.*[az]): Positive look ahead says: "There must be a lowercase letter". (?=.*[az]):正向向前表示:“必须有一个小写字母”。 That's fine.没关系。
  • (?=.*[AZ]): Positive look ahead says: "There must be an uppercase letter". (?=.*[AZ]): 正面展望表示:“必须有一个大写字母”。 That's fine.没关系。
  • .: Anything goes. 。: 什么都行。 That's obviously wrong.这显然是错误的。
  • {6,32}: Length requirement. {6,32}:长度要求。

So Arpit's answer:所以 Arpit 的回答是:

^(?=.*\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.因此,由于禁止使用空格,因此不再需要负面展望。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM