a regular expression generator for number ranges

前端 未结 9 2156
长情又很酷
长情又很酷 2021-02-04 05:56

I checked on the stackExchange description, and algorithm questions are one of the allowed topics. So here goes.

Given an input of a range, where begin and ending number

9条回答
  •  闹比i
    闹比i (楼主)
    2021-02-04 06:18

    I recently had a requirement where I needed to develop a "Regular Expression Generator For Number Ranges" using Java and I have developed a full solution which is posted on IdeOne and class is called ideone.java -- Source Code on ideone.com. Code on ideone is heavily commented and it uses the same algorithm as posted by other users, so I will only highlight the changes and features added or issues fixed. I used part of solutions provided in answers by Bezmax (concept), arcy (overall code and idea of generating RegEx range as pairs) and coproc (using recursion for generating RegEx pairs, instead of method used by arcy). Thanks to all the three folks.

    There are two public methods provided by Ideone.java, which implement the RegExGenerator logic - one accepts string numeric ranges and the other accepts integer number ranges.

    generateRegEx(String begStr, String endStr)
    generateRegEx(int beg, int end)
    

    Both of the aforementioned public methods call generateRegExCommon method, which in turn calls the getRegExPairsRecursion method (same implementation as provided by coproc's answer), to generate a list containing numbers in pairs which represent lower and upper end of valid RegEx ranges. It then calls formatPairsToRegEx method to convert the RegEx pairs to actual RegEx ranges which may contain prefix of zeros to match the input length, if there were zeros in the input. If the input did not contain leading zeros or if integer input was used, no leading zeros would be added to the output ranges. The output is available as a list of Array of strings, where each entry/element is a valid Regular expression numeric range:

    regexArray - String Array where each element is a valid regular expression range.
    regexList  - List of String elements where each element is a valid regular expression range.
    

    Figure below shows sequence diagram of a sample execution of Java code (ideone.java) with input and output at each stage. The example used has Input Range of numeric strings with leading zeros where Lower range value is "0006" and upper range is "0977". Output as shown in the figure below is:

    000[6-9]
    00[1-9][0-9]
    0[1-8][0-9][0-9]
    09[0-6][0-9]
    097[0-7]
    

    Code provides the following benefits:

    • Single comprehensive solution combining the best of all answers and algorithms.
    • Print statements which help in debugging the code and can be easily converted to any logging framework trace/debug statements, instead of System.out.
    • Fixed the problem where low range of 0 was not working with other answers.

提交回复
热议问题