$& - Refers to the entire text of the current pattern match.
$` - Refers to the text to the left of the current pattern match.
$' - Refers to the text to the right of the current pattern match.
To see these references in action, I set up the following demo. In this code, our replacement execution is completely non-functional; it is meant only to elucidate the values contained within each replacement reference:
As you can see in the above code, we are matching each individual group of digits within the phone number contained within the source text. When we execute the String.replace() method, we're simply replacing the captured number with each of the above $-based values.
When we run the above code, we get the following console output:
My number is |--  [My number is ] [-555-1234.] --|-|--  [My number is 212-] [-1234.] --|-|--  [My number is 212-555-] [.] --|.
This is a little bit hard to read, so I'm going to break out the replacement portion of each match on its own line:
|--  [My number is ] [-555-1234.] --|
|--  [My number is 212-] [-1234.] --|
|--  [My number is 212-555-] [.] --|.
As you can see, the $& referred to the entire matched pattern (in our case, that was also the first captured group and could be referred to as $1). The &` referred to the entire text value of the source to the left of the current match. And, the $' referred to the entire text value of the source text to the right of the current match.
Want to use code from this post? Check out the license.