2

I am attempting to write a .Net Regex for more than 2 consecutives letters.

aa - fine
Aa - fine
aaa - not allowed
Aaa - not allowed

I am new to regex, but this is what I have pieced together so far.

if (Regex.IsMatch(Password, @"/[^A-Za-z]{2}/"))
    return "Password cannot contain 3 consecutive same letters"; 

I am not sure if this is close or not.

dan_vitch
  • 4,477
  • 12
  • 46
  • 69
  • I think what you looking for is simply `(.)\1\1`. The regex you have will match 2 any letters like `ab`. – Ilia G Mar 18 '12 at 17:26
  • @Ilia G - `(.)\1\1` works for `AAA` and `aaa`, but NOT `Aaa` or `aaA`. D'oh! – ridgerunner Mar 18 '12 at 18:02
  • 2
    @ridgerunner `Regex.Match("bOooga", @"(.)\1\1", RegexOptions.IgnoreCase)` Alternativelly you could upper/lower case the input before running the regex like ruakh did. – Ilia G Mar 18 '12 at 18:07
  • @Ilia G - No, just adding `IgnoreCase` will not fix this. The single char that is captured in `$1` is either lower or upper and `\1` will be always be the exact same letter. The expression: `(.)\1\1` can only match the same one character, three times in a row. The only way that this expressions will work is if the string is first forced to all-upper or all-lower case befor performing the match. – ridgerunner Mar 19 '12 at 15:52
  • @ridgerunner The code snippet I posted works as is. Feel free to try it out. – Ilia G Mar 20 '12 at 02:21

1 Answers1

6

You need to remove the slashes (why are they there? this is not PHP) and you could use the ignore case flag. Like:

Regex.Match(pw, @"(?i)(.)\1\1")

Which is same as:

Regex.Match(pw, @"(.)\1\1", RegexOptions.IgnoreCase)

As commented by Ilia G.

Qtax
  • 33,241
  • 9
  • 83
  • 121