double_espresso
double_espresso

Reputation: 115

Remove multi-line C style /* comments */ using Perl regex

How do I remove multi-line C style comments like:

/* comments
   comments
   comments
   comments */

I am able to remove comments in one line like /* comments */ by using several codes provided in other questions.

s#/\*[\s\S]*?\*/##sg;
s#/\*(.*?)\*/##sg;
s#/\*[^*]*\*+([^/*][^*]*\*+)*/|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)#defined $2 ? $2 : ""#gse

All three regexes above do not work with multi-line comments. How can they be handled?

Upvotes: 3

Views: 1547

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174766

I would do like,

perl -0777pe 's/\/\*(?:(?!\*\/).)*\*\/\n?//sg' file

Example:

$ cat fi
/* comments
   comments
   comments
   comments */
bar
$ perl -0777pe 's/\/\*(?:(?!\*\/).)*\*\/\n?//sg' fi
bar

Upvotes: 5

Related Questions