DEV Community

Discussion on: VS Code: Search-and-Replace Regex

Collapse
 
marcohern profile image
Marco Hernandez

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 tries with '$this->$1 = $$1', it does not work properly. So how do we go about it?

Collapse
 
rfornal profile image
bob.ts

Article written and posted ... here: dev.to/rfornal/vs-code-search-and-...

Collapse
 
rfornal profile image
bob.ts

OK. I see a couple of things going on here.

First, you state you are using '$var', for replacement, this should be '(\$[a-zA-Z]*)'.

  • The parens allow for the selection as $1
  • The backslash allows VS Code to correctly find '$var' in the content as REGEX.

Second, to use '$this->$1 = $$1' as a pattern for replacement ...

  • The selection above in my first response would need changed to something like this '\$([a-zA-Z0-9]*)' to allow for selection of text that starts with a dollar sign.
  • The replacement pattern should be changed to '\$this->=>$1 = $$$1'. The dollar sign in the replacement is "escaped" using the double-dollar-sign (see HERE)
Collapse
 
rfornal profile image
bob.ts

Having provided a reply, I think I'll write this up as a separate article for clarity. I'll post here when it's complete ... probably in the next day or two. Thanks for the GOOD question!