Time and time again I see $1 and $2 being used in code. What does it mean? Can you please include examples?
-
1This may be helpful to you: [Grouping & Backreferences](http://www.regular-expressions.info/brackets.html) – Justin Morgan - On strike May 12 '11 at 18:47
-
Similar question: [How to explain “$1,$2” in Javascript when using regular expression?](https://stackoverflow.com/questions/16702924/how-to-explain-1-2-in-javascript-when-using-regular-expression) – user2314737 Apr 06 '19 at 09:53
-
In above question, I've found answers from "Niels Keurentjes" and "Mark Chorley" easy to understand for new users of JS – vikramvi Jul 18 '19 at 07:50
2 Answers
When you create a regular expression you have the option of capturing portions of the match and saving them as placeholders. They are numbered starting at $1
.
For instance:
/A(\d+)B(\d+)C/
This will capture from A90B3C
the values 90
and 3
. If you need to group things but don't want to capture them, use the (?:...)
version instead of (...)
.
The numbers start from left to right in the order the brackets are open. That means:
/A((\d+)B)(\d+)C/
Matching against the same string will capture 90B
, 90
and 3
.

- 208,517
- 23
- 234
- 262
-
It would in Perl, but I don't think Ruby supports that kind of back-tracking. – tadman Jun 06 '11 at 14:30
-
-
This is better than other explanations I could find, but it's still missing an example of actually using $1, $2, etc. – Steve Aug 10 '22 at 19:14
-
@Steve You just put those in the substitution string. It's all in [the documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/n). – tadman Aug 10 '22 at 19:33
This is esp. useful for Replacement String Syntax (i.e. Format Strings) Goes good for Cases/Case Foldings for Find & Replaces. To reference a capture, use $n where n is the capture register number. Using $0 means the entire match. Example : Find: (<a.*?>)(.*?)(</a>) Replace: $1\u$2\e$3

- 333
- 1
- 4