Countdown regex as number of repetitions

Is there a way to build a regex that works like this:

Match an integer as group 1 , then match \1 integers.

This (\d+)(\s+\d+){\1} unfortunately not allowed, but I find this a good description of what I'm trying to achieve.

+8
regex
source share
1 answer

You can do something like this

 var numbers = "3 7 6 5 4 3 2 1"; // list of numbers var iter = numbers.split(" ")[0] // get first number numbers = numbers.substr(iter.length+1) // chop off first number, and the space that follows it you can comment var rex = new RegExp("(?:\\d(?: |$)){" + iter + "}","") // create regex alert((numbers.match(rex)||[]).join("\n")) // a sample alert that joins the array to a string with an element on each line 

Alternatively, if you want the first digit to determine the number of entries in the same array, several changes make it possible

 var numbers = "3 7 6 5 4 3 2 1"; // list of numbers var iter = numbers.split(" ")[0] // get first number var rex = new RegExp("(?:\\d(?: |$)){" + (+iter+1) + "}","") // create regex alert((numbers.match(rex)||[]).join("\n")) // a sample alert that joins the array to a string with an element on each line 
+1
source share

All Articles