DEV Community

Regex in VSCode: My favorite hacks

Recently, I needed to implement a gradual feature rollout. I had a spreadsheet with a list of 300 company IDs in the first column, which would be part of this phased release.

My task was to take each ID individually and insert it into an update query to execute directly in the database.

At first, I considered multiple different methods to make it. Then I remembered of VSCode combination with Regular Expressions, a technique I had heard about but never actually tried. This situation was the perfect opportunity to test it out.

My idea with this article is to show you how combining VSCode with regular expressions can assist you.

Reasons To Use

One of the most common uses is finding and replacing text, removing duplicates, and making adjustments across multiple files. You can see other applications in the following documentation: https://learn.microsoft.com/en-us/visualstudio/ide/using-regular-expressions-in-visual-studio?view=vs-2022

I will focus on the methods I have used that have helped me.

How to use?

To Enable the regular expressions in the function finding, press:

  1. Command + F (MacOS) or Ctrl + F (Windows, Linux)
  2. Option + Command + F (⌥⌘F) or Ctrl + H (Windows, Linux)

This command will open the dialog box with Toggle Replace enabled:

image dialog box

After this, you can check the option to "Use the Regular Expression”, usually represented by a .* icon, with the command:

  1. Option + Command + R (⌥⌘R) or Alt+E (Windows, Linux)

image icon

My Favorite Cheats

Find and Replace

My first favorite cheats is to separate numbers with commas and quotes:

Search: (\d+)

Replace: "$1”, (or no quotes $1,)

This will wrap the number in quotes and add a comma after it.

Transform multiples line into one:

Search: \n
Replace: Use a space or nothing (depending on your preference).

first cheat

Comment specific search across multiple files

Replace: // $0

image specific search

Find instances for classes

To find instances where a class is being instantiated, use the following pattern:

Search: new\s+User\s*\(

find instance

How did I find these regular expressions?

I usually search for them after testing on regex101.com or by Googling examples.
Try exploring and adapting these techniques to your workflow.

Regex can work like magic!

Top comments (0)