正则表达式匹配Asp.Net中的密码字段

时间:2012-04-23 05:43:41

标签: c# asp.net regex

我正在使用Asp.Net/C#,我正在使用RegularExpressionValidator来匹配密码字段。我的要求是我需要用户输入一个至少7个字符长的密码,它可以包含任何密码字母和数字字符的组合,但它应该严格包含一个非字母数字字符,任何人都可以建议我如何实现这一点。 欢迎任何建议。谢谢你

3 个答案:

答案 0 :(得分:3)

试试这个

String[] words = { "Foobaar", "Foobar1", "1234567", "123Fooo", "Fo12!", "Foo12!", "Foobar123!", "!Foobar123", "Foo#bar123" };

foreach (String s in words) {

    Match word = Regex.Match(s, @"
          ^                        # Match the start of the string
            (?=                    # positive look ahead
                [\p{L}\p{Nd}]*     # 0 or more letters or digits at the start
                [^\p{L}\p{Nd}]     # string contains exactly one non-digit, non-letter
                [\p{L}\p{Nd}]*     # 0 or more letters or digits after the special character 
            $)                     # till the end of the string
            .{7,}                  # match 7 or more characters
          $                        # Match the end of the string
        ", RegexOptions.IgnorePatternWhitespace);
    if (word.Success) {
        Console.WriteLine(s + ": valid");
    }
    else {
        Console.WriteLine(s + ": invalid");
    }
}
Console.ReadLine();

\p{L}是一个带有“letter”属性的unicode代码点

\p{Nd}是一个带有“digit”属性的unicode代码点

答案 1 :(得分:1)

((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{7,20})


(           # Start of group
  (?=.*\d)      #   must contains one digit from 0-9
  (?=.*[a-z])       #   must contains one lowercase characters
  (?=.*[A-Z])       #   must contains one uppercase characters
  (?=.*[@#$%])      #   must contains one special symbols in the list "@#$%"
              .     #     match anything with previous condition checking
                {7,20}  #        length at least 7 characters and maximum of 20 
)

here复制。

答案 2 :(得分:0)

我使用以下内容来满足我的需求^([\w]*[(\W)]{1}[\d]*)$,这允许密码以字母开头任意次,然后密码必须只包含一个非字母数字字符一次,后跟一个数字任意次数。

相关问题