开发者

Regex for "Does not contain four or more repeated characters"

My experience with regular expressions is limited and I've been reading various tutorials and posts on negation and negative lookahead, etc, but nothing seems to quite match my situation.

I'm trying to create an attribute in ASP.NET MVC3 for password complexity. Part of the validation includes a minimum number of repeated characters. For the current project the limit is 3, but I want to generalize it.

Initially, I was using @"(.)\1{3,}" to test for 4 or more repeated characters and then negating that result. I can't do that n开发者_高级运维ow because I need to create a ModelClientValidationRegexRule object, which will only work with positive results. As such, the negation must be done inside the regex itself. Every way I've tried to use negative lookahead fails, e.g. @".*(?!(.)\1{3,})".

Any ideas?


Turn the problem around: a character can be followed by at most 3 of the same. Then it must be followed by something else. Finally, the whole string must consist of sequences like this. In the perl flavor:

^((.)\2{0,3}(?!\2))*$


You need to put the .* inside the lookahead:

(?!.*?(.)\1{3,})

The way you're doing it, the .* consumes the whole string, then the lookahead asserts that there aren't four of the same character after the end of the string, which of course is always true.

I used a non-greedy star in my lookahead because it seemed more appropriate, but greedy will work too--it just has to be inside the lookahead.

I'm assuming this is just one of several lookaheads, that being the usual technique for validating password strength in a regex. And by the way, while regex-negation is appropriate, you would have gotten more responses to your question much more quickly if you had used the regex tag as well.


I used the simple ^(.)(?!\1\1){8,}$ for a 8 or more character that doesn't have any characters that repeat more than twice.


I think, use this regex .*(.).*\1+.* to matches existd repeated characters. But for four, depend on you.

Good luck!


Find char in the group then match repeats

(.).*(\1{3,})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜