Find and Replace with Regex in VS Code

Published: Thursday, September 17, 2020

Greetings, friends! Ever needed to replace lines of text with regular expressions (regex)? There are copious ways of achieving text replacement through regex. You can use popular command line utilities such as awk and sed, or write scripts in practically any programming language that supports regex. Sometimes, we don't want to leave VS Code and want to make simple text replacements. Let's get started!

First, we'll create a file named file-1.js with the following contents:

js
Copied! ⭐️
console.log('Hello World!')

Then, we'll create a second file named file-2.js with the following contents:

js
Copied! ⭐️
console.log('Hello Universe!')

Notice that the first file uses single quotes and the second file uses double quotes. Suppose we want to replace Hello with Greetings, in both lines and make sure that we use single quotes for both files. Therefore, file-1.js will contain:

js
Copied! ⭐️
console.log('Greetings, World!')

And file-2.js will contain:

js
Copied! ⭐️
console.log('Greetings, Universe!')

Let's see how to do this in VS Code! Open up the search bar in VS Code using Cmd+Shift+F (on Mac) or Ctrl+Shift+F (on Windows). Then, you'll see an arrow on the left-hand side of the search bar. Click on this arrow to reveal the "Replace" feature in the search bar.

screenshot showing how to reveal the replace feature in the search bar

Next, you can click on the .* symbol to activate the regex feature. We will use the following regex pattern in the VS Code search bar:

md
Copied! ⭐️
["']hello\s(.*)!['"]

Notice that it's case-insensitive by default and notice that we're using a capture group as indicated by the parentheses inside the regex. You can press enter while in the search bar to perform a search using this regex pattern.

We can make use of the capture group inside the "Replace" field and type:

md
Copied! ⭐️
'Greetings, $1!'

The $1 will act as a placeholder for everything captured in our capture group. If you had more than one capture group, you could use $2, $3, etc.

If you press enter, you'll see that VS Code shows you a preview of what all text will be replaced in each file where a match occurred. Once you hit the "Replace All" button, it'll prompt you if you really want to make this change. Click "Confirm" and then you're done!

screenshot of using regex to find and replace all matches in vs code

Regex101 is a fantastic website for testing out your regex patterns. It helps you identify what text is found in your capture groups as well. I encourage everyone to give it a try!

screenshot of using regex101 website to test regex patterns

Resources