避免重复连续炭的正则表达式,但不包括一个特定的char
我正在与python一起学习很多正则是言论,而我在允许没有连续4个或更多重复的字符的允许测试用例方面挣扎着,我在互联网上找到了简单的解决方案,但我需要评估重复的字符,不包括“不包括”,不包括“” - 例如:例如:
bic-hota // Valid
bichota // Valid
bichota1234 // Valid
bich222ota // Valid, sequence "222" with length of 3 is allowed
bichota2222 // Invalid because have "2222" and isn't allowed length of 4 or more
bichota22-22 // Invalid because have "2222" (ignore the '-') and isn't allowed length of 4 or more
在上一个测试案例中,您可以看到序列“ 22-22”,我需要忽略“ - ”整个序列的序列之间的“”,我已经搜索了如何解决这个问题,我使用了非捕捉组(?: - ?)
,但这不起作用:(
^(?![\w]*([\w])(?:-?)\1{3,})[\w-]+$
我的正则是什么问题以及如何修复它?
测试用例:< a href =“ https://regexr.com/6p0ca” rel =“ nofollow noreferrer”> https://regexr.com/6p0ca
I am learning a lot of Regex with Python, and I am struggled with a regex for allow test cases where doesn't have consecutive 4 or more repeated chars, I have found easy solutions in Internet but I need evaluate the repeated chars excluding the "-" char, for example:
bic-hota // Valid
bichota // Valid
bichota1234 // Valid
bich222ota // Valid, sequence "222" with length of 3 is allowed
bichota2222 // Invalid because have "2222" and isn't allowed length of 4 or more
bichota22-22 // Invalid because have "2222" (ignore the '-') and isn't allowed length of 4 or more
In the last test case, you can see the sequence "22-22", I need ignore the "-" between the sequence for validate whole the sequence, and I have searched about how to solve this and I have use the Non-capture group (?:-?)
but this doesn't works :(
^(?![\w]*([\w])(?:-?)\1{3,})[\w-]+$
What is wrong with my regex and how to fix it?
Test cases: https://regexr.com/6p0ca
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用此迫切号:
regex demo
regex详细信息:
^
:开始(?!
:开始负LookAhead。*
:匹配字符的任意长度(\ w)
:匹配一个字符并在组#1中捕获(?: - ?\ 1){3}
:匹配可选-
,然后进行反向引用到组#1。重复此组3次。)
:结束负面lookahead。+
:匹配任何字符的1+只允许单词字符和连字符使用:
You may use this regex:
RegEx Demo
RegEx Details:
^
: Start(?!
: Start negative lookahead.*
: Match any length of characters(\w)
: Match a character and capture in group #1(?:-?\1){3}
: Match optional-
followed by back-reference to group #1. Repeat this group 3 times.)
: End negative lookahead.+
: Match 1+ of any charactersTo allow only word characters and hyphens use:
或匹配不需要的:
[^\ w-]
一个 not a word字符或连字符(\ w)( - ?\ 1){3}
四重复\ w
with 可选|^$
之间的连字符|^$
a href =“ https://www.regular-expressions.info/anchors.html” rel =“ nofollow noreferrer”>空字符串如果需要( demo )< a href =“ https://regex101.com/r/oldlo6/1” rel =“ nofollow noreferrer”>请参阅此演示在Regex101 (
\ n
仅用于多行演示),这种方式甚至可以在某些失败消息中显示匹配的零件。
Or match the unwanted:
[^\w-]
a character that is not a word character or hyphen(\w)(-?\1){3}
four repeated\w
with optional hyphen in between|^$
can be further attached for empty string positives if needed (demo)See this demo at regex101 (the
\n
is just used for the multiline demo)This way the matched part could even be displayed in some fail-message.