有没有一种方法可以构建一个正则表达式,实现以下功能:
匹配整数作为组
1
,然后匹配\1
个整数。
很不幸,这个(\d+)(\s+\d+){\1}
是不被允许的,但我认为它描述了我正在尝试实现的内容。
有没有一种方法可以构建一个正则表达式,实现以下功能:
匹配整数作为组
1
,然后匹配\1
个整数。
很不幸,这个(\d+)(\s+\d+){\1}
是不被允许的,但我认为它描述了我正在尝试实现的内容。
您可以像这样做:
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
或者,如果你想要第一个数字来定义在同一数组中出现的次数,只需进行一些更改即可实现。
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
$s = '3 4 5 6 7 8 9 10';
$s =~ /(\d+)\s+((??{"(\\s*\\d+){$^N}"}))/;
print "$1\n$2\n"
打印
3
4 5 6
\s+\d+
n
次)。 - Kobi