Leo.W Leo.W - 1 year ago 82
C# Question

Regular expression for 2 alphabets & 6 number

I have a password rule to be follow, required the password must contain 2 alphabet (upper or lowercase) & 6 numbers, and the whole length is expected to equal 8 symbols.

Here's the samples that should pass:


And the samples that should fail:


And I need a regular expression to fit this rule.

Answer Source

A regex approach can be multiple, here are 2: 1) require the legnth of 8 chars with a lookahead like (?=.{8}$) and use a consuming pattern allowing zero or more digits before a letter twice, and then match zero or more letters, 2) match 8 letters or digits, but use a lookahead restriction to match 2 alphabets.

Example 1:



  • ^ - start of string
  • (?=.{8}$) - the length should be 8 non-newline symbols only
  • (?:\d*[a-z]){2} - 2 sequences of 0+ digits followed with 1 letter
  • \d* - 0+ digits
  • $ - end of string.

See the regex demo

Example 2:



  • ^ - start of string
  • (?=(?:\d*[a-z]){2}\d*$) - there must be 2 sequences of 0+ digits and a letter followed with 0+ digits up to the end of string
  • [\da-z]{8} - 8 digits or letters
  • $ - end of string.

See the regex demo 2

Note that to enable case insensitive mode, you can prepend the pattern with (?i) / RegexOptions.IgnoreCase flag, and if you need to only match ASCII digits, use RegexOptions.ECMAScript or replace \d with [0-9].

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download