5

我只想接受没有任何子字符串连续重复三次的字符串。子字符串事先不知道。例如,“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;
}
4

3 回答 3

10

尝试这个:

bool result = Regex.IsMatch(input, @".*(.+).*\1.*\1.*");

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

完整解释:

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

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

bool result = Regex.IsMatch(input, @".*(.+)\1\1.*");

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

Non-consecutive: 312ms
Consecutive: 246ms

使用此程序进行了测试:

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);
    }
}
于 2013-05-31T13:43:52.593 回答
0

正则表达式是我攻击这个的方式:

static void Main(string[] args)
        {
            string text = "C# is the best language there is in the world.";
            string search = "the";
            Match match = Regex.Match(text, search);
            Console.WriteLine("there was {0} matches for '{1}'", match.Groups.Count, match.Value);
            Console.ReadLine();
        }

如何使用正则表达式组查找多次出现?

于 2013-05-31T13:36:53.750 回答
-1
Regex.Matches( "a4a4a4123",  "a4" ).Count >= 3
于 2013-05-31T13:36:48.857 回答