Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript backreference followed by number

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.

like image 390
Asad Saeeduddin Avatar asked Nov 06 '12 09:11

Asad Saeeduddin


People also ask

What is a regex Backreference?

A backreference in a regular expression identifies a previously matched group and looks for exactly the same text again. A simple example of the use of backreferences is when you wish to look for adjacent, repeated words in some text. The first part of the match could use a pattern that extracts a single word.

How do I get rid of square brackets in regex?

Brackets can be removed from a string in Javascript by using a regular expression in combination with the . replace() method.

Can I use named capture groups?

Mixing named and numbered capturing groups is not recommended because flavors are inconsistent in how the groups are numbered. If a group doesn't need to have a name, make it non-capturing using the (?:group) syntax.


2 Answers

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" );
like image 153
Xophmeister Avatar answered Oct 09 '22 04:10

Xophmeister


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");
like image 34
Nate Cook Avatar answered Oct 09 '22 02:10

Nate Cook