A
Asen Bozhilov
I would like to have function which automatically generates ranges.
For example range 0 - 25 could be written as:
(?:2[0-5]|1[0-9]|[0-9])
I don't want to do that every time and I wrote a function which
generate that sequence.
function toRange(num) {
var n, size,
digit, i,
j, reg,
arr = [];
while (num > 0) {
n = num;
size = Math.floor(Math.log(num) / Math.LN10);
j = size;
i = 10;
reg = '';
while ((digit = n % 10) == 9) {
if (i < num) {
reg += '[0-9]';
}
else {
reg = '[1-9]' + reg;
}
n = Math.floor(n / 10);
i *= 10;
j--;
}
if (j > 0) {
reg = ('' + num).slice(0, j) + (digit ? '[0-' + digit +
']' : '0') + reg;
}
else if (digit) {
reg = (digit > 1 ? '[1-' + digit + ']' : '1') + reg;
}
if (i >= num) {
num = Math.pow(10, size) - 1;
}
else {
num -= (num % i) + 1;
}
arr.push(reg);
}
arr.push(0);
return '(?:' + arr.join('|') + ')';
}
toRange(255); //(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9]|0)
toRange(26); //(?:2[0-6]|1[0-9]|[1-9]|0)
Any suggestions or improvements are welcome.
For example range 0 - 25 could be written as:
(?:2[0-5]|1[0-9]|[0-9])
I don't want to do that every time and I wrote a function which
generate that sequence.
function toRange(num) {
var n, size,
digit, i,
j, reg,
arr = [];
while (num > 0) {
n = num;
size = Math.floor(Math.log(num) / Math.LN10);
j = size;
i = 10;
reg = '';
while ((digit = n % 10) == 9) {
if (i < num) {
reg += '[0-9]';
}
else {
reg = '[1-9]' + reg;
}
n = Math.floor(n / 10);
i *= 10;
j--;
}
if (j > 0) {
reg = ('' + num).slice(0, j) + (digit ? '[0-' + digit +
']' : '0') + reg;
}
else if (digit) {
reg = (digit > 1 ? '[1-' + digit + ']' : '1') + reg;
}
if (i >= num) {
num = Math.pow(10, size) - 1;
}
else {
num -= (num % i) + 1;
}
arr.push(reg);
}
arr.push(0);
return '(?:' + arr.join('|') + ')';
}
toRange(255); //(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9]|0)
toRange(26); //(?:2[0-6]|1[0-9]|[1-9]|0)
Any suggestions or improvements are welcome.