匹配不包含超过 x 个连续字符的字符串的正则表达式是什么 [英] What is the regex to match a string not containing more than x consecutive characters

查看:96
本文介绍了匹配不包含超过 x 个连续字符的字符串的正则表达式是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想匹配不超过 3 个连续重复的相同字符的字符串.所以:

I want to match strings that do not contain more than 3 of the same character repeated in a row. So:

  • abaaaa [不匹配]​​
  • abawdasd [匹配]
  • abbbbasda [不匹配]​​
  • bbabbabba [匹配]

是的,对包含连续字符进行正则表达式匹配会更容易和更整洁,然后在代码中否定它.但是,在这种情况下,这是不可能的.

Yes, it would be much easier and neater to do a regex match for containing the consecutive characters, and then negate that in the code afterwards. However, in this case that is not possible.

我想把问题展开成x个连续的字符,以便可以扩展到一般情况,使问题和答案更有用.

I would like to open out the question to x consecutive characters so that it can be extended to the general case to make the question and answer more useful.

在这种情况下支持负前瞻.

Negative lookahead is supported in this case.

推荐答案

使用反向引用的负前瞻:

Use a negative lookahead with back references:

^(?:(.)(?!\1\1))*$

使用您的示例查看现场演示.

(.) 捕获第 1 组中的每个字符,否定前瞻断言接下来的 2 个字符是不是捕获字符的重复.

(.) captures each character in group 1 and the negative look ahead asserts that the next 2 chars are not repeats of the captured character.

这篇关于匹配不包含超过 x 个连续字符的字符串的正则表达式是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆