Getting all possible consecutive 4 digit numbers from a 10 digit number

前端 未结 2 1262
孤独总比滥情好
孤独总比滥情好 2020-12-07 03:37

I am trying to make a regex to get all the possible consecutive 4 digit numbers from a 10 digit number. Like

num = \"2345678901\";
<         


        
2条回答
  •  孤城傲影
    2020-12-07 04:00

    Do you absolutely need to use Regex? The same operation can be achieved much more quickly using a simple loop.

    private IEnumerable getnums(string num)
    {
        for (int i = 0; i < num.Length - 3; i++)
        {
            yield return num.Substring(i, 4);
        }
    }
    
    private IEnumerable DoIt(string num)
    {
        var res = Regex.Matches(num, @"(?=(\d{4}))")
                    .Cast()
                    .Select(p => p.Groups[1].Value)
                    .ToList();
        return (IEnumerable)res;
    
    }
    

    On average the simple loop takes about half the time of the RegEx version.

    static void Main(string[] args)
    {
    
        var num = "2345678901";
    
        Stopwatch timer = new Stopwatch();
    
        timer.Start();
        foreach (var number in getnums(num))
        {
            // Yum yum numbers
        }
        timer.Stop();
        Console.WriteLine(timer.Elapsed.Ticks);
    
        timer.Reset();
    
        timer.Start();
        foreach (var number in DoIt(num))
        {
            // Yum yum numbers
        }
        timer.Stop();
        Console.WriteLine(timer.Elapsed.Ticks);
    }
    

提交回复
热议问题