Version 0 of HOW TO - Remove C style comments

Updated 2005-09-02 23:29:18

Given a file which contains C style comments (i.e. /* .... */ ) the following procedure will remove the comments. This procedure actually also will correctly remove comments that are imbeded (i.e. /* ... /* ... */ ... */) which I don't believe is legel in C.

 proc stripComments { text {replacement ""} } {
     # remove all comments that don't have an imbedded '*'
     # characters except at the beginning and end of the comment
     regsub -all {[/][*]+([\n]?[^*]*[\n]?)*?[*]+[/]} $text ${replacement} text

     # recursively remove all comments that don't have any imbedded '/' characters
     while {[regsub -all {[/][*]+([\n]?[^/]*[\n]?)*?[*]+[/]} $text ${replacement} text] ne 0} {continue}
     return $text
 }

 set result [stripComments ${data} "#comment removed\n"]

The procedure could stand some more testing but it works on the cases I have tried.

Tom Krehbiel