Skip to content

Instantly share code, notes, and snippets.

@illtellyoulater
Last active October 20, 2023 04:49
Show Gist options
  • Save illtellyoulater/fbd133baef0797772023cbb42592e378 to your computer and use it in GitHub Desktop.
Save illtellyoulater/fbd133baef0797772023cbb42592e378 to your computer and use it in GitHub Desktop.
REGEXP FOR SINGLE & MULTI-LINE COMMENTS (JS / C / C# / JAVA / etc.)

REGEXP FOR SINGLE & MULTI-LINE COMMENTS ( JS / C / C# / JAVA / etc... )

Tested in VS Codium and at https://regex101.com

\/\*[\s\S\n]*?\*\/|\/\/.*$

This will correctly match:

  // single line comments

  /**
   * multi
   * line
   * comments
   * // including nested inline comments 
   * and without tripping on URL slashes (https://www.example.com)
   */

  /* single line comments written using multi-line delimiters */

  // /* single line comments written using MLDs and within a regular single line comment */
It can also be useful to prefix the regexp with two additional * (one at the beginning and one after the | ) which will also select all horizontal white-spaces preceding both single and multi-line comments:
 *\/\*[\s\S\n]*?\*\/| *\/\/.*$

will_select_this_area_as_well_together_with // the content of a deeply nested comment

This can come handy when you have to do some external work on the comments (e.g. translating them). By copying the spaces too, when you'll paste the comments back in the code you can be sure they'll slide back into their original position (column-wise).

That said, in order to avoid errors and make those additional sections more clear, it should be also possible to rewrite it using [[:space:]]* like so:

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

however it seems that unfortunately VS Code/Codium do not support this syntax yet, so I'm sticking with the * form.

Hope it helps!

Note: if you are testing this on https://regex101.com/ make sure to set the g and m flags using the switch located after the "hard coded" / at the end of the expression.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment