正则表达式以检测字符串中的重复

时间:2009-06-03 09:45:18

标签: c# regex

是否可以使用正则表达式检测重复的数字模式?

例如,如果我有以下字符串“034503450345”,是否可以匹配重复序列0345?我觉得这超出了正则表达式的范围,但我想我还是会问这里,看看我是否错过了什么。

5 个答案:

答案 0 :(得分:19)

此表达式将匹配一个或多个重复组:

(.+)(?=\1+)


这是相同的表达式,(使用注释,因此它仍然可以直接用作正则表达式)。

(?x)  # enable regex comment mode
(     # start capturing group
.+    # one or more of any character (excludes newlines by default)
)     # end capturing group
(?=   # begin lookahead
\1+   # match one or more of the first capturing group
)     # end lookahead


要匹配特定模式,请将.+更改为该模式,例如\d+代表一个或多个号码,或\d{4,}代表4个或更多号码。

要匹配特定数量的模式,请将\1+更改为\1{4},重复四次。

为了让重复不会彼此相邻,您可以在前瞻中添加.*?

答案 1 :(得分:9)

是的,你可以 - 这是一个Python测试用例

import re
print re.search(r"(\d+).*\1", "8034503450345").group(1)
# Prints 0345

正则表达式说“找到一些数字序列,然后找到任何数量的其他东西,然后再找到相同的序列。”

在几乎没有相关的说明中,这是我最喜欢的正则表达式之一 - 素数检测器:

import re
for i in range(2, 100):
    if not re.search(r"^(xx+)\1+$", "x"*i):
        print i

答案 2 :(得分:8)

只需在RichieHindle的(正确)答案中添加注释:

请注意,虽然Python的regexp实现(以及许多其他实现,例如Perl)可以做到这一点,但这不再是狭义上的正则表达式。

您的示例不是常规语言,因此无法通过纯正则表达式处理。参见例如优秀的Wikipedia article了解详情。

虽然这主要只是学术兴趣,但有一些实际后果。与这种情况相比,真正的正则表达式可以更好地保证最大运行时间。所以你可能会在某些时候遇到性能问题。

并不是说它不是一个好的解决方案,但你应该意识到你正处于正则表达式(即使是扩展形式)能够的极限,并且可能想要在出现问题时考虑其他解决方案。

答案 3 :(得分:2)

这是C#代码,它使用反向引用构造来查找重复的数字。它将与034503450345,123034503450345,034503450345345,232034503450345423一起使用。正则表达式更容易理解。

/// <summary>
/// Assigns repeated digits to repeatedDigits, if the digitSequence matches the pattern
/// </summary>
/// <returns>true if success, false otherwise</returns>
public static bool TryGetRepeatedDigits(string digitSequence, out string repeatedDigits)
{
    repeatedDigits = null;

    string pattern = @"^\d*(?<repeat>\d+)\k<repeat>+\d*$";

    if (Regex.IsMatch(digitSequence, pattern))
    {
        Regex r = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
        repeatedDigits = r.Match(digitSequence).Result("${repeat}");
        return true;
    }
    else
        return false;
}

答案 4 :(得分:0)

使用正则表达式重复:    杆{2,} 查找带有两个或更多条形的文本:    BARBAR    barbarbar    ...

相关问题