Javascript反向引用后跟数字 [英] Javascript backreference followed by number
问题描述
如果我有一个正则表达式,例如13个捕获组,我如何指定包含第一个反向引用后跟文字3的替换字符串?
If I had a regular expression with, say 13 capturing groups, how would I specify a replacement string that contained the first backreference followed by the literal '3'?
var regex = /(one)(2)(3)(4)(5)(6)(7)(8)(9)(10)(11)(12)(13)/;
"one2345678910111213".replace(regex,"$13");
//Returns "13". How do I return "one3"?
我能找到的最接近的问题是这一个,但它与perl有关,并且不包括硬编码的文字。
The closest question I could find was this one, but it pertains to perl and did not include a hardcoded literal.
还看了 docs ,但没有明确说明或在示例中演示。
Also had a look at the docs on MDN, but there was nothing explicitly stated or demonstrated in the examples.
推荐答案
好抓!我能想出的唯一解决方案是:
Good catch! The only solution I've been able to come up with is:
var regex = /(one)(2)(3)(4)(5)(6)(7)(8)(9)(10)(11)(12)(13)/;
"one2345678910111213".replace(regex, function(match, $1) { return $1 + "3"; } );
编辑我看了 ECMAScript规范,看起来没有回调就可以实现。一些RegExp替换引擎 - 例如Python - 有一个 \ g
构造(对于group),你可以使用类似的东西替换字符串中的\g {1} 3
;但JavaScript只使用 $ nn
。也就是说,如果你有超过9个捕获组,你可以使用两位数的反向引用来消除歧义,如下所示:
EDIT I looked up the ECMAScript spec and it looks like this is possible without a callback. Some RegExp replacement engines -- Python, for example -- have a \g
construct (for "group"), where you can use something like \g{1}3
in the replacement string; but JavaScript just uses $nn
. That is, if you've got more than 9 capturing groups, you can use a two-digit back reference to remove the ambiguity, like so:
"one2345678910111213".replace(regex, "$013" );
这篇关于Javascript反向引用后跟数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!