Version 2 of HOW TO - Remove C style comments

Updated 2005-09-03 17:10:58

The following procedure will remove C style comments (i.e. /* .... */ ) from text.

 proc removeComments { text {replacement ""} } {
    regsub -all {[/][*].*?[*][/]} $text ${replacement} text
    return $text        
 }

If you need to remove C style comments that are imbedded (i.e. /* ... /* ... */ ... */) use the following procedure.

 proc removeImbeddedComments { text {replacement ""} } {
     set text [string map  {"/*" \x80 "*/" \x81} $text]
     while {[regsub -all {\x80[^\x80\x81]*?\x81} $text ${replacement} text]} {continue}
     set text [string map  {\x80 "/*" \x81 "*/"} $text]
     return $text
 }

Use Examples:

 removeComments ${data} "#comment-removed#"

 removeImbeddedComments ${data} "#comment-removed#"

Test Cases:

 ##### Simple Comments #####
 # test-1
 /**/
 /* */
 /* text1 */
 # test-2
 text1 /**/ text2 /* */ text3 /* comment */
 # test-3
 /*
 */
 text1
 /*
     */
 text2
     /*
      */
 # test-4
 text1 /*
 */ text2

 text1 /*
     */ text2
 # test-5
 /* comment
 */
 /*
 comment
 */
 /*
 comment */
 ##### Imbedded Comments #####
 # test-1
 text1 /*/*/**/*/*/ text2
 # test-2
 text1 /*/**//**//*/**//**//**/*/*/ text2
 # test-3
 text1 /* comment /* comment /* comment */ comment */ comment */ text2
 # test-4
 text1
 /*
 text2
 text3 /* comment */
 text4 /*
         comment
         comment /* comment */
         comment
       */
 text5
 */
 text5
 # test-5
 text1
 /*
  comment ///
     /*
      comment ///
         /*
          comment ///
          comment ***
          */
      comment ***
      */
  comment ***
  */
 text2
 # test-6
 text1 * / / *
 /*
  comment ///
     /*
      comment ///
         /*
          comment ///
          comment ***
          */
      comment ***
      */
  comment ***
  comment ///
     /*
      comment ///
         /*
          comment ///
          comment ***
          */
      comment ***
      comment ///
         /*
          comment ///
          comment ***
          */
      comment ***
      */
  comment ***
  */
 text2
 # test-7 (dangling comments)
 */ /*

Tom Krehbiel