Jun 23 '20 ~ 14 ~ 2 mins

Regex search and replace with VS Code

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 do I have to update each manually? Thankfully the answer is no! Regex search and replace 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-.


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, 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

App 2

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, showing 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 saving heaps of time and ensuring we don't accidentally miss any!

Find more examples of regex search and replace see this Stack Overflow question or check out my other post which shows another example of refactoring code using Regex Search and Replace.

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

Follow me on Twitter @ScooperDev or Tweet about this post.

Headshot of Stephen Cooper

Hi, I'm Stephen. I'm a senior software engineer at AG Grid. If you like my content then please follow / contact me on Twitter and say hello!