/

Search and Replace in VS Code Using Regular Expressions

Search and Replace in VS Code Using Regular Expressions

I recently encountered a situation where I needed to make a significant change in my website’s repository. Within my markdown files, I had included images with spaces in their filenames. However, due to an update in Hugo, the markdown library I was using (Blackfriday) was no longer supported, and only Goldmark, which does not allow spaces in image filenames, was supported.

To update my website and stay current with Hugo, I needed to update all the image links. Instead of manually editing each file, I decided to use the find and replace functionality in VS Code, which supports regular expressions.

After some experimentation, I created a regular expression with two capturing groups: one for the alt text and one for the filename. The regular expression looked like this:

1
!\[(.+)\]\((.*\s+.*)\)

In the replace box, I used $1 to reference the alt text and $2 to reference the filename. This allowed me to easily update the image links throughout my markdown files.

For images without alt text, I used the following regular expression:

1
!\[\]\((.*\s+.*)\)

And the replacement string ![](/images/vscode-search-replace-regex/$1) worked for those images.

I arrived at these regular expressions by referencing my JavaScript Regular Expressions tutorial, which I wrote some time ago but still find to be a helpful resource. I also utilized search engines and online regex testing tools like regex101 to fine-tune my expressions.

While regular expressions can sometimes feel like magic, they can be incredibly powerful for tasks like search and replace. In this case, they allowed me to efficiently update the image links across my markdown files.

Tags: search and replace, VS Code, regular expressions, markdown, alt text, image links