Convert integer numeric interval to regex

后端 未结 3 1217
轻奢々
轻奢々 2020-12-06 21:48

SO,

I\'m looking for a solution about the problem - how to convert integer interval to regex. Suppose I have two numbers, A and B. Both of

3条回答
  •  忘掉有多难
    2020-12-06 22:43

    As others have already told you, this is not a very good idea. It will not be faster than just matching all integers and filter them afterwards. But I will answer your question anyway.

    Depending on how large the interval is you can let the regex engine optimize it for you, so you just output a |-separated list of values. This can be minimized algorithmically with basic algorithms from finite automata theory.

    This may be too memory-intensive for large intervals. In that case you can match all numbers of different lengths from A and B in one go. In your example, all numbers of 6-7 digits are easily matched with [0-9][1-9]{5,6}. Now you have the border cases left, which you can create recursively by (for the A side in this case, I have not included the base case of the recursion):

    1. Let S be A.
    2. Let f be first digit of S, g=f+1, and n be (digits of S)-1
    3. Add a segment to the regex for digits larger than f of: [g-9][0-9]{n}
    4. Add a segment for numbers starting with f: f(recursive call starting from step 2, with S=the rest of digits of S)

    So for A=123 we would end up with something like (spaces only added for "readability"):

    ([2-9][0-9]{2}) | (1(([3-9][0-9]{1}) | (2(([4-9]) | 3))) )
    

提交回复
热议问题