How to search patterns in arbitrary sequences?

后端 未结 1 2003
天涯浪人
天涯浪人 2021-02-19 03:55

Regex is on string\'s only, but what if that functionality can be extended to not only character but objects or even further to functions? Suppose our object\'s will be integers

相关标签:
1条回答
  • 2021-02-19 04:25

    String inheritance

    After some research, I found that idea to optimize existing Regex is impossible. This is because even if I know index in string, I still don't have access to possible states in Regex automaton, which I should look to filter unneccesary calculations.

    ORegex

    As to answer, I decided to implement my own engine similar to Microsoft Regex engine. Syntax is the same as Microsoft Regex syntax. You can find more information and examples at Nuget and github:

    Currently, it supports basic Regex engine features and also some of popular features like lookahead and capturing.

    Example

    public static bool IsPrime(int number)
    {
        int boundary = (int)Math.Floor(Math.Sqrt(number));
        if (number == 1) return false;
        if (number == 2) return true;
        for (int i = 2; i <= boundary; ++i)
        {
            if (number % i == 0) return false;
        }
        return true;
    }
    
    public void PrimeTest()
    {
        var oregex = new ORegex<int>("{0}(.{0})*", IsPrime);
        var input = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
        foreach (var match in oregex.Matches(input))
        {
            Trace.WriteLine(string.Join(",", match.Values));
        }
    }
    
    //OUTPUT:
    //2
    //3,4,5,6,7
    //11,12,13
    
    0 讨论(0)
提交回复
热议问题