5

I am in need of a Sublime Text 2 friendly regex that would allow me to search for all comments within a file.

The comments are all following this basic structure /* <anything> */

Thanks for taking the time to help :)

Mad-Chemist
  • 487
  • 6
  • 18
  • possible duplicate of [using regex to remove comments from source files](http://stackoverflow.com/questions/2319019/using-regex-to-remove-comments-from-source-files) – Wajahat Feb 28 '14 at 21:37

3 Answers3

17

Search for:

(?s)/\*.*?\*/

This allows you to match comments that spreads over multiple lines.

The (?s) turns on "single line" mode, which makes . matches any character without exception (by default, . excludes line separators).

This assumes that there is no /* or */ inside a string literal.

Or if you want a bullet-proof solution, you may want to take a look at this question:

Can we make use of syntax highlighting feature to remove all comments from a source file in SublimeText?

Community
  • 1
  • 1
nhahtdh
  • 55,989
  • 15
  • 126
  • 162
  • 2
    For a multiline match, this would be simpler: `/\*[\s\S]+?\*/` – CAustin Feb 28 '14 at 22:21
  • @CAustin Note: If you use `calc()` and multiply inside or you're using sass and multiply in it or have comments that include `*` that solution doesn't work. At least didn't work for me. – Ivanka Todorova Aug 18 '16 at 13:52
14

Something like this should work:

\/\*.+?\*\/

I'm not super-familiar with Sublime Text, but this would work in Notepad++, and I believe the regex implementation is basically the same. If I'm wrong, feel free to let me know.

Edit: Per CAustin's helpful tip, you can also just do this (without the escaping of the forward slashes):

/\*.+?\*/
elixenide
  • 44,308
  • 16
  • 74
  • 100
  • You don't need to escape the forward slashes, so this would work too: `/\*.+?\*/` – CAustin Feb 28 '14 at 22:19
  • @CAustin Good to know; I will tweak accordingly. – elixenide Feb 28 '14 at 22:20
  • 6
    `\/\*[\s\S]+?\*\/` also captures multiline comments. @CAustin mentioned it in the comments of another answer, but I spent some minutes on regexr.com to figure it out because I didn't look further than the accepted answer. To save anyone from the same fate, I thought I'd double post that here -.- – robro Mar 02 '15 at 11:43
0

I think this code is better:

\/\*[^(?:\*\/)]*\*\/
MohsenB
  • 1,669
  • 18
  • 29