How to search and replace with regex in VS Code

By

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:

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:

VS Code search panel using a regular expression with two capturing groups

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:

![$1](<$2>)

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

VS Code replacement field using $1 and $2 for captured text

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.

VS Code showing hundreds of regular expression matches across Markdown files

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.

Tagged: Tools ยท All topics
~~~

Related posts about tools: