I need to generate, at run time, a regular expression that will match a range of numeric values.
For example: At run time I may discover that I need a regular expression matching all the files in the “range” a-261-b.something to a-543-b.something.
I need to generate a regular expression that will match all of this files. Any ideas?
I need it in Java, so if anyone know any Java-specific way to so this, it’s also acceptable.
Whether or not regular expressions are well suited for this task is debatable. Most people would probably argue that it’s not.
As I understand it however, you have no choice as the API you’re using takes a regular expression as argument, so here goes…
Code
Usage
Explanation
A brief explanation of the code follows.
Ranges on the shape
0000–abcdandabcd–9999First we note that matching ranges such as
0000–abcdis fairly easy.An expression covering for instance
000–527can be expressed as[0-4]followed by two arbitrary digits, or5followed by00–27(which is resolved recursively!)Ranges on the shape
1000–abcdandabcd–9999are just as easy.Lower limit, upper limit of different lengths.
If the “from”-number is shorter than the “to”-number it is fairly straight forward.
Assume for instance that the
from-number has 3 digits and theto-number has 7 digits. The expression can then be composed as follows:from–999(as described above),4,5or6digit number:[1-9][0-9]{3-5}, or1000000–to(as described above)Lower limit / upper limit of equal lengths.
This is the trickiest situation (still not that tricky though!)
The solution is, again, best described by an example. Consider the range
273–548. The expression can be composed by the following parts:2followed by73–99(latter part described above),[34]followed by any two digits, or5followed by00–48(latter part described above)