c# Regex.Match 与 .Net Regex Tester 结果不匹配

标签 c# regex

我需要将用户的密码限制为至少 8 个字符以及小写、大写、数字和特殊字符的混合。我已经使用 .Net Regex Test 网站进行测试,并得出以下解决方案。从下面的两个链接中您可以看到 mer220d#没有匹配项,但是 Mer220d#完美匹配,但在我使用完全相同的 Regex 的 .Net 代码中,它们都返回 true。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace BOR.Security.CheckConstraints
{
    public class CheckPasswordConstraint
    { 

        public static bool passwordValidation(string passwordToCheck)
        {
            string pattern = @"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*\W)[a-zA-Z0-9\S]{8,}$";
            Match m = Regex.Match(passwordToCheck.TrimEnd(), pattern, RegexOptions.IgnoreCase);
            return m.Success;
        }
    }
}

你能告诉我遗漏了什么吗?

最佳答案

您应该删除 RegexOptions.IgnoreCase,因为 (?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]) 并且只需要任意 1 个 ASCII 字母,小写或大写。

此外,[a-zA-Z0-9\S] = \S 因为字母和数字都是非空白字符。

此外,您必须在两端修剪字符串,使用.Trim(),而不是.TrimEnd()

此外,建议使用constrast的原理在密码正则表达式中使它们更有效率。

使用

字符串模式 = @"^(?=[^a-z][a-z])(?=[^A-Z][A-Z])(?=\D*\d)(?=\w*\W)\S{8,}$"; 匹配 m = Regex.Match(passwordToCheck.Trim(), pattern);

解释

  • ^ - 字符串的开始
  • (?=[^a-z]*[a-z]) - 必须至少有 1 个小写 ASCII 字母
  • (?=[^A-Z]*[A-Z]) - 必须至少有 1 个大写 ASCII 字母
  • (?=\D*\d) - 必须至少有 1 个数字
  • (?=\w*\W) - 必须至少有 1 个非单词字符
  • \S{8,} - 8 个或更多非空白字符(无空格,但接受所有其他字符)
  • $ - 字符串结尾。

关于c# Regex.Match 与 .Net Regex Tester 结果不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50722341/

相关文章:

c# - 在 Azure 搜索文档中使用枚举

c# - CustomValidator OnServerValidate 不工作

c# - 异步 TDD - 测试类 block

regex - 使用 html5 模式属性对 pin 进行验证

c# - 如何在方法调用中传递动态参数

c# - 在没有客户端请求的情况下在客户端套接字上发送数据

c++ - 你如何打印 std::regex?

regex - JScript 正则表达式 : start of line doesn't work?

regex - Bash - grep 提取以指定字符串结尾的单词;在找不到匹配项的地方留下空格

c++ - Perl正则表达式中 "~"标记有什么用?