Regex for “Does not contain four or more repeated characters”

梦想的初衷 提交于 2019-12-01 08:07:37

问题


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, e.g. @".*(?!(.)\1{3,})".

Any ideas?


回答1:


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))*$



回答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.




回答3:


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




回答4:


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

Good luck!




回答5:


Find char in the group then match repeats

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


来源:https://stackoverflow.com/questions/4754637/regex-for-does-not-contain-four-or-more-repeated-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!