检查字符串中是否有连续的重复子字符串

Ily*_*sky 5 c# string

我想只接受没有连续三​​次重复的子字符串的字符串.子串事先不知道.例如,"a4a4a4123"包含"a4"; "abcdwwwabcd" - "w"; "abcde" - 有效,无三重复.

我试图自己实现它,但这仅适用于带有一个字母的子字符串:

public bool IsValid(string password)
{
    var validate = true;
    char lastLetter = ' ';
    var count = 1;

    for (int pos = 0; pos < password.Length; pos++)
    {
        if (password[pos] == lastLetter)
        {
            count++;

            if (count > 2)
            {
                validate = false;
                break;
            }
        }
        else
        {
            lastLetter = password[pos];
            count = 1;
        }
    }

    return validate;
}
Run Code Online (Sandbox Code Playgroud)

It'*_*ie. 10

试试这个:

bool result = Regex.IsMatch(input, @".*(.+).*\1.*\1.*");
Run Code Online (Sandbox Code Playgroud)

基本上,它检查一个或多个字符的模式是否在同一个字符串中出现3次或更多次.

完整说明:

首先,它匹配字符串开头的0个或多个字符.然后它捕获一组一个或多个.然后它匹配0或更多,然后再次组.然后再次 0或更多,然后再次捕获.然后再次0或更多.

如果您要求字符串是连续的,请尝试以下操作:

bool result = Regex.IsMatch(input, @".*(.+)\1\1.*");
Run Code Online (Sandbox Code Playgroud)

此外,一些性能测试结果:

Non-consecutive: 312ms
Consecutive: 246ms
Run Code Online (Sandbox Code Playgroud)

测试是通过这个程序完成的:

using System;
using System.Diagnostics;
using System.Text.RegularExpressions;

class Program
{
    public static void Main(string[] args)
    {
        string input = "brbrbr";
        Regex one = new Regex(@".*(.+).*\1.*\1.*");
        for (int i = 0; i < 5; i++)
        {
            bool x = one.IsMatch(input); //warm regex up
        }
        Stopwatch sw = Stopwatch.StartNew();
        for (int i = 0; i < 100000; i++)
        {
            bool x = one.IsMatch(input);
        }
        sw.Stop();
        Console.WriteLine("Non-consecutive: {0}ms", sw.ElapsedMilliseconds);
        Regex two = new Regex(@".*(.+)\1\1.*");
        for (int i = 0; i < 5; i++)
        {
            bool x = two.IsMatch(input); //warm regex up
        }
        Stopwatch sw2 = Stopwatch.StartNew();
        for (int i = 0; i < 100000; i++)
        {
            bool x = two.IsMatch(input);
        }
        sw.Stop();
        Console.WriteLine("Consecutive: {0}ms", sw2.ElapsedMilliseconds);
        Console.ReadKey(true);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这是一个有趣的例子,说明所谓的"常规"表达式是什么样的.根据定义,常规语言可以由具有*固定*可用存储量的程序匹配,但是该模式匹配器可以"记住"任意长的子串. (2认同)