本文介绍了正则表达式:如何匹配没有任何字符重复 3 次的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个验证输入字符串的模式.验证规则不允许任何字符连续重复超过 3 次.

I'm trying to make a single pattern that will validate an input string. The validation rule does not allow any character to be repeated more that 3 times in a row.

例如:

Aabcddee - 有效.

Aabcddde - 无效,因为有 3 个 d 字符.

Aabcddde - is not valid, because of 3 d chracters.

目标是提供一个 RegExp 模式,它可以匹配上述示例之一,但不能同时匹配两者.我知道我可以使用反向引用,例如 ([a-z])\1{1,2} 但这仅匹配顺序字符.我的问题是我无法弄清楚如何为此制作单一模式.我试过了,但我不太明白为什么它不起作用:

The goal is to provide a RegExp pattern that could match one of above examples, but not both. I know I could use back-references such as ([a-z])\1{1,2} but this matches only sequential characters. My problem is that I cannot figure out how to make a single pattern for that. I tried this, but I don't quite get why it isn't working:

^(([a-z])\1{1,2})+$

在这里,我尝试匹配在内部组中重复 1 或 2 次的任何字符,然后如果该内部组重复多次,则匹配该内部组.但它不是那样工作的.

Here I try to match any character that is repeated 1 or 2 times in the internal group, then I match that internal group if it's repeated multiple times. But it's not working that way.

谢谢.

推荐答案

从你的问题我知道你想要匹配

From your question I get that you want to match

  • 仅由来自 [A-Za-z] AND
  • 的字符组成的字符串
  • 只有没有长度为 3 或更多的相同字符序列的字符串

那么这个正则表达式应该可以工作:

Then this regexp should work:

^(?:([A-Za-z])(?:(?!\1)|\1(?!\1)))+$

(perl 中的示例)

这篇关于正则表达式:如何匹配没有任何字符重复 3 次的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 01:15