How to Find and Replace Groups with Regex in VSCode

Published Aug 15, 2022

Let’s see how we can use regular expressions in VSCode’s Find and replace text functionality.

Suppose we have the following text somewhere in our VSCode workspace.

~<corgi>~
~<shih-tzu>~

Remember to select the .* icon in the VSCode search bar to use regular expressions.

1. Replace all matched text

We can match text using the following regex.

~<.*>~

We can, of course, replace that text with whatever we want.

hello dog

In this scenario, both ~<corgi>~ and ~<shih-tzu>~ will be replaced with hello dog.

2. Replace groups of matched text

Here, we want to find and replace groups of text using parentheses (). Each group (from left to right) can be referenced in the replacement text using $1, $2, $3, and so on.

With the following regular expression:

~<(.*)>~

We can just use the following replacement text:

hello $1

~<corgi>~ will be replaced with hello corgi and ~<shih-tzu>~ will be replaced with hello shih-tzu.