DEV Community

Cover image for VS Code: Search-and-Replace Regex with Dollar-Sign
bob.ts
bob.ts

Posted on • Edited on

VS Code: Search-and-Replace Regex with Dollar-Sign

In a previous article about VS Code, Search-and-Replace using RegEx, I had a question that prompted me to create this article so that I can remember what I did ...

The Question

What if I need to replace something with $? For example, replace $var with $this->var = $var, the regex to search is easy, the problem is the replacement. I (have tried this) with $this->$1 = $$1 (and) it does not work properly. So how do we go about it?

The Solution

The solution, as I see it is actually in two parts. First, we need to properly select the content for replacement. Then, second, we need to define the replacement, accounting for the dollar-sign ...

Selecting the Content

When I started breaking down the question in my head, I saw some content like the following ...



$var;
$content;
$question;


Enter fullscreen mode Exit fullscreen mode

... the assumption being that this should be changed into ...



$this->var = $var;
$this->content = $content;
$this->question = $question;


Enter fullscreen mode Exit fullscreen mode

So, this means I need to capture the text after the dollar sign. As stated in the question, this is pretty straight forward. There are many ways to do this. I chose ...



\$([a-zA-Z0-9]*)


Enter fullscreen mode Exit fullscreen mode

Replacing the Content

The dollar-sign after the equal sign seems to be where the main concern of the question comes from. I will admit that it took me a few minutes to get my head around the issue of escaping it.

Original Attempt

First, I tried this replacement RegEx ...



$this->$1 = $$1


Enter fullscreen mode Exit fullscreen mode

... this is shown in the question and makes sense; however, the result is ...



$this->var = $1


Enter fullscreen mode Exit fullscreen mode

Escaping the Dollar-Sign

... then, I tried escaping the dollar-sign after the equal-sign ...



$this->$1 = \$$1


Enter fullscreen mode Exit fullscreen mode

... however, the result is not quite what I expected ...



$this->var = \$var


Enter fullscreen mode Exit fullscreen mode

Proper Escaping of the Dollar-Sign

While this is closer, there is clearly something wrong with this approach. I then started searching for how to properly escape the dollar-sign in a RegEx Search-and-Replace.

I found the following ...

You need to escape the $ replacement with $$ and then use the substitution value of $1.

The resulting expression should be: $$$1

The Solution

And, here's the answer ...



$this->$1 = $$$1


Enter fullscreen mode Exit fullscreen mode

... try it out, it works!

Top comments (1)

Collapse
 
code2be profile image
Ahmed Hosny

Thanks ! helped me alot.