简体   繁体   中英

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 now 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, eg @".*(?!(.)\\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 think, use this regex .*(.).*\\1+.* to matches existd repeated characters. But for four, depend on you.

Good luck!

在组中查找字符然后匹配重复

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

我使用简单的^(.)(?!\\1\\1){8,}$表示 8 个或更多字符,并且没有任何重复超过两次的字符。

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