具有反向引用的正则表达式作为重复计数

Nox*_*itu 9 regex

有没有办法构建一个可以如下工作的正则表达式:

将整数作为组1匹配,然后匹配\1整数.

(\d+)(\s+\d+){\1}不幸的是,这是不允许的,但我发现它很好地描述了我想要实现的目标.

Reg*_*Joe 2

你可以做这样的事情

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
Run Code Online (Sandbox Code Playgroud)

或者,如果您想要定义同一数组中出现次数的第一个数字,则可以进行一些更改

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
Run Code Online (Sandbox Code Playgroud)