Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex with backreference as repetition count

Tags:

regex

Is there any way to construct a regex that would work as follows:

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

This (\d+)(\s+\d+){\1} unfortunetly isn't allowed, but I find it a good description of what i am trying to achive.

like image 281
Noxitu Avatar asked Apr 19 '15 10:04

Noxitu


1 Answers

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 that defines the number of occurrences in the same array, a few 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
like image 197
Regular Jo Avatar answered Oct 29 '22 00:10

Regular Jo