“不包含四个或更多重复字符”的正则表达式
我对正则表达式的经验有限,我一直在阅读有关否定和否定前瞻等的各种教程和帖子,但似乎没有什么与我的情况完全匹配。
我正在尝试在 ASP.NET MVC3 中创建一个属性以实现密码复杂性。验证的一部分包括最小数量的重复字符。对于当前项目来说,限制是 3,但我想概括一下。
最初,我使用 @"(.)\1{3,}"
来测试 4 个或更多重复字符,然后否定该结果。我现在无法执行此操作,因为我需要创建一个 ModelClientValidationRegexRule
对象,该对象仅适用于积极的结果。因此,否定必须在正则表达式本身内部完成。我尝试使用负向先行的每种方法都失败了,例如@".*(?!(.)\1{3,})"
。
有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
扭转问题:一个字符后面最多可以跟 3 个相同的字符。然后它后面必须跟着别的东西。最后,整个字符串必须由这样的序列组成。在 Perl 风格中:
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:
您需要将
.*
放入前瞻中:按照您的方式,
.*
会消耗整个字符串,然后Lookahead 断言在字符串末尾之后不存在四个相同的字符,这当然总是正确的。我在前瞻中使用了非贪婪的星号,因为它看起来更合适,但贪婪也可以工作——它只需位于前瞻内。
我假设这只是几个前瞻之一,这是在正则表达式中验证密码强度的常用技术。顺便说一句,虽然 regex-negation 是合适的,但如果您也使用了 regex 标签,您会更快地得到更多对您的问题的答复。
You need to put the
.*
inside the lookahead: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.
我使用简单的
^(.)(?!\1\1){8,}$
来表示 8 个或更多字符,且不包含任何重复两次以上的字符。I used the simple
^(.)(?!\1\1){8,}$
for a 8 or more character that doesn't have any characters that repeat more than twice.我认为,使用这个正则表达式
.*(.).*\1+.*
来匹配现有的重复字符。但对于四个人来说,就看你了。祝你好运!
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