EDDYMENS

Published 2 weeks ago

How To Remove All Comments From Code In VS Code Using Regex

Table of contents

Its the third time I have seen a person spend over a minute deleting comments from code they generated using a certain tool that shall not be named.

This seems to have become a common task people indulge in, So I thought, why not show you how to wipe out all comments in one clean swoop? And maybe pick up some free traffic while am at it.

So here we go.

First Step: Search and Replace

VS Code search and replace bar [→]

We will be using VS Code's [↗] built-in Search and Replace feature, you can open it using:

  • Ctrl + F on Windows
  • Cmd + F on macOS.

Next, click the > arrow to reveal the Replace input.

Then click the .* icon to turn on Regex mode [↗], this allows you to use patterns to match text.

Removing // and / ... / style comments

To remove all comments of the form:

01: // comment here 02: 03: /** 04: * Multi-line 05: * comment 06: * */

Paste the following into the Find field:

01: //.*?$|/\*[\s\S]*?\*/

Leave the Replace field empty, and click the last button on the right to remove all matches.

Removing # Style Comments

Similarly, to get rid of all Python style comments, thus comments of the form:

01: # comment 1 02: # comment 2

Use this regex:

01: #.*$

Again, leave Replace empty, and hit the last button.

Removing <\/!-- ... --> Style Comments

For HTML or XML-style comments like:

01: <!-- this is a comment -->

Use this pattern:

01: <!--[\s\S]*?-->

Leave Replace empty, and hit that last button.

Conclusion

With those three patterns, you can clean out most comments.

Here is another article you might like 😊 How To Override The Default 404 Error Page In Laravel 12