最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Javascript backreference followed by number - Stack Overflow

programmeradmin8浏览0评论

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"?

The closest question I could find was this one, but it pertains to perl and did not include a hardcoded literal.

Also had a look at the docs on MDN, but there was nothing explicitly stated or demonstrated in the examples.

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"?

The closest question I could find was this one, but it pertains to perl and did not include a hardcoded literal.

Also had a look at the docs on MDN, but there was nothing explicitly stated or demonstrated in the examples.

Share Improve this question edited May 23, 2017 at 12:01 CommunityBot 11 silver badge asked Nov 6, 2012 at 9:46 user1726343user1726343
Add a comment  | 

2 Answers 2

Reset to default 14

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"; } );

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" );

Just to add a concise answer for future reference:

Backreferences have at most two digits, so to use backreference #1 followed by a literal numeral, call it "01" instead of "1":

"one2345678910111213".replace(regex,"$013");
发布评论

评论列表(0)

  1. 暂无评论