Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

vscode
productivity
communitycreator

Regex search and replace with VS Code

Stephen Cooper

I wanted to upgrade ag-grid across a number of apps. Standard search and replace did not work due to variations in package names and versions. So, did I have to update each manually? Thankfully, the answer was no – Regex search and replace came to the rescue.

Too many variations

For example, each of the apps below have different versions and package names. How do we upgrade all ag-grid packages to the latest release of 23.2.0 ? We cannot do a search and replace unless we go one at a time:

 App 1
"@ag-grid-enterprise/all-modules": "22.1.4",
"@ag-grid-community/angular": "22.1.5",

App 2
"@ag-grid-community/all-modules": "22.1.3",
"@ag-grid-community/angular": "22.1.4",

App 3
...

Regex match to the rescue

VS Code lets you search with regexes. Select the third option in the search bar and write your regex.

Enable Regex Search

This is the regex that I used to find all the packages starting with @ag-grid- .

(@ag-grid-.*:).*,

You can see this regex in action on Regex 101 to try it out for yourself.

Capture Groups

Now comes the amazing part! The part of the regex in the () is called a capture group and you can reference it the replace box. This means that you can say whatever matched this capture group and leave that the same when you make the replacement.

In our case, this is whatever ag-grid package name we already have.

Capture Groups for $1

App 1
@ag-grid-enterprise/all-modules":
@ag-grid-community/angular":

App 2
@ag-grid-community/all-modules":
@ag-grid-community/angular":

We refer to the capture group with the syntax $1 .

If you have multiple capture groups then you would use $1, $2, $3, and so on to refer to the capture groups in the order they are defined.

So we can then write our search and replace as follows.

Find: (@ag-grid-.*:).*,

Replace: $1 "23.2.0",

Here is the replacement preview – it shows the versions updated for different packages at the same time, thanks to our regex.

Replace Preview

This is so powerful as we can do a single regex search and replace and update all ag-grid packages at once, which saves heaps of time and ensures that we won’t accidentally miss any!

Hope this saves you as much time as it did for me!

RELATED TAGS

vscode
productivity
communitycreator
RELATED COURSES

View all Courses

Keep Exploring