Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 580
double_espresso Avatar asked Apr 09 '26 16:04

double_espresso


1 Answers

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
like image 185
Avinash Raj Avatar answered Apr 12 '26 08:04

Avinash Raj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!