How to search and replace with regex in VS Code
By Flavio Copes
Use regular expressions in VS Code search and replace, capture parts of each match with parentheses, and reuse them with $1 and $2 in the replacement.
VS Code can search and replace text using regular expressions. Enable the .* button in the search box, enter your pattern, then use $1, $2, and so on to reuse captured text in the replacement.
Search with a regular expression
Open the Search view to work across the entire project:
- macOS:
Cmd-Shift-F - Windows and Linux:
Ctrl-Shift-F
Expand the replace field, then click the .* button to enable regular expressions.
For example, this pattern finds a Markdown image and captures its alt text and URL:
!\[([^\]]*)\]\(([^)]+)\)
Parentheses create the two capturing groups:
$1contains the alt text$2contains the image URL

Reuse capture groups in the replacement
Suppose you want to wrap every Markdown image URL in angle brackets. This helps when a URL contains spaces.
Use this replacement:

VS Code inserts the text captured by the first and second groups into each replacement.

Review the preview before selecting Replace All. A broad regular expression can change more files than you intended.
A practical example
I used this technique to update hundreds of Markdown image links containing spaces. Editing them by hand was not an option.
The search pattern found each image, while the replacement kept the existing alt text and path. Only the surrounding syntax changed.

If capturing groups are new to you, read my JavaScript regular expressions guide. You can also experiment with a smaller sample in my regex tester before changing a project.
Related posts about tools: