DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

C++ Style Comment Stripper

02.19.2007
| 5162 views |
  • submit to reddit
        // This scirpt either removes the C++ style comments or places them
// just before the line in which they occur
// for ex:
//
//      int i=0, sum;    //This is some comment(embedded)
//
// after conversion:
//      //This is some comment(embedded)
//      int i=0, sum;

# comm_stripper
#
# Description :
#
#   This scirpt either removes the C++ style comments or places them
#   just before the line in which they occur
#   for ex:
#
#       int i=0, sum;    //This is some comment(embedded)
#
#   after conversion:
#       //This is some comment(embedded)
#       int i=0, sum;

import re
import os

#comm_re = re.compile(r"(\s*)(.*)(//.*)")

comm_re = re.compile(r"(\s*)(.*?)(//.*)")
ext_re  = re.compile(r"\.(cpp|h|hpp|c|icc)$")
out_ext = ".out"

TRUE  = 1
FALSE = 0

def comm_strip(file_name, keep_comment=TRUE):
    lines = file(file_name).readlines()
    out_lines = []

    out_filename = file_name + out_ext
    fout = open(out_filename, "w")

    for line in lines:
        match = comm_re.match(line.rstrip())

        if(match):
            if keep_comment:
                #print "%s%s" % (match.group(1), match.group(3))
                out_lines.append("%s%s\n" % (match.group(1), match.group(3)))
            if match.group(2):
                #print "%s%s" % (match.group(1), match.group(2).rstrip())
                out_lines.append("%s%s\n" % (match.group(1), match.group(2).rstrip()))
        else:
            #print line.rstrip()
            out_lines.append(line)

    out_lines.append("\n\n")
    fout.writelines(out_lines)
    print "File %s => %s" % (file_name, out_filename)
    print "-"*80

print os.getcwd()
file_names = os.listdir(".")
flag=TRUE

for file_name in file_names:
    match_ext = ext_re.search(file_name)

    if match_ext :
        comm_strip(file_name, flag)

print "Done!"
    

Comments

Snippets Manager replied on Mon, 2007/02/19 - 9:20am

hey brewbuck, thanks for posting ;-) yes you are correct, i am not handling/checking the condition you have mentioned. i have simply coded that script for my own scenario in which there was no need of checking that ... anyways may be some one will post in for that so that it will help us all. Thanks

Snippets Manager replied on Tue, 2007/02/20 - 1:39pm

What happens with code like this? char *bad = "two slashes: //";