Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does $1, $2, etc. mean in Regular Expressions?

Tags:

javascript

Time and time again I see $1 and $2 being used in code. What does it mean? Can you please include examples?

like image 513
david Avatar asked May 12 '11 18:05

david


People also ask

What does $1 do in regex?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

What is $1 and $2 in JavaScript?

A piece of JavaScript code is as follows: num = "11222333"; re = /(\d+)(\d{3})/; re. test(num); num. replace(re, "$1,$2");

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

What is $1 in replace JS?

In your specific example, the $1 will be the group (^| ) which is "position of the start of string (zero-width), or a single space character". So by replacing the whole expression with that, you're basically removing the variable theClass and potentially a space after it.


1 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.

like image 79
tadman Avatar answered Sep 21 '22 18:09

tadman