Leo.W - 1 year ago 68

C# Question

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:

`a123456b`

1a2b3456

aa123456

123ab456

And the samples that should fail:

`1abcdefg2`

a1234567b

abcdefgh

12345678

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:

```
^(?=.{8}$)(?:\d*[a-z]){2}\d*$
```

*Details*:

`^`

- 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:

```
^(?=(?:\d*[a-z]){2}\d*$)[\da-z]{8}$
```

*Details*:

`^`

- 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]`

.