简体   繁体   English

“不包含四个或更多重复字符”的正则表达式

[英]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.我正在尝试在ASP.NET MVC3为密码复杂性创建一个属性。 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.对于当前项目,限制为 3,但我想概括一下。

Initially, I was using @"(.)\\1{3,}" to test for 4 or more repeated characters and then negating that result.最初,我使用@"(.)\\1{3,}"来测试 4 个或更多重复字符,然后否定该结果。 I can't do that now because I need to create a ModelClientValidationRegexRule object, which will only work with positive results.我现在不能这样做,因为我需要创建一个ModelClientValidationRegexRule对象,它只会产生积极的结果。 As such, the negation must be done inside the regex itself.因此,否定必须在正则表达式本身内部完成。 Every way I've tried to use negative lookahead fails, eg @".*(?!(.)\\1{3,})" .我尝试使用负前瞻的每一种方式都失败了,例如@".*(?!(.)\\1{3,})"

Any ideas?有任何想法吗?

Turn the problem around: a character can be followed by at most 3 of the same.扭转问题:一个字符最多可以跟 3 个相同的字符。 Then it must be followed by something else.然后它必须跟着别的东西。 Finally, the whole string must consist of sequences like this.最后,整个字符串必须由这样的序列组成。 In the perl flavor:在 perl 风格中:

^((.)\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.顺便说一下,虽然regex-negation是合适的,但如果你也使用了regex标签,你会更快地得到更多对你的问题的回答。

I think, use this regex .*(.).*\\1+.* to matches existd repeated characters.我认为,使用这个正则表达式.*(.).*\\1+.*来匹配现有的重复字符。 But for four, depend on you.但对于四个,取决于你。

Good luck!祝你好运!

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM