简体   繁体   中英

C# regx expression can anyone solve

  1. At least one lower case letter,
  2. At least one upper case letter,
  3. At least special character,
  4. At least one number
  5. At least 8 characters length

problem is showing error at "/d" in regx pattern

private void txtpassword_Leave(object sender, EventArgs e) {
    Regex pattern = new Regex("/^(?=.*[a-z])(?=.*[A-Z])(?=.*/d)(?=.*[#$@!%&*?])[A-Za-z/d#$@!%&*?]{10,12}$/");
    if (pattern.IsMatch(txtpassword.Text)) {
        MessageBox.Show("valid");
    } else {
        MessageBox.Show("Invalid");
        txtpassword.Focus();
    }
}

Try this instead :

^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})

Tests

In regex, the backslash is used to escape. So instead of /d it should have been \\d.

But you could also just use [0-9] instead.

^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])(?=.*?[^a-zA-Z0-9\s])\S{8,}$

Also, when using backslashes in a string.
Then either double backslash. Or use a verbatim string. Fe @"foobar"

More about that in this SO post .

Example C# code:

string[] strings = { "Foo!bar0", "foobar", "Foo bar 0!", "Foo!0" };

Regex rgx = new Regex(@"^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])(?=.*?[^a-zA-Z0-9\s])\S{8,}$");

foreach (var str in strings){
    Console.WriteLine("[{0}] {1} valid.", str, rgx.IsMatch(str) ? "is" : "is not");
}

Returns:

[Foo!bar0] is valid.
[foobar] is not valid.
[Foo bar 0!] is not valid.
[Foo!0] is not valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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