Never been to DZone Snippets before?

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

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

C++ Style Comment Stripper

// 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!"

Regular expression to match an HTML comment

// description of your code here
This snippet uses the non-greedy matcher, and the "m" option to treat strings as multi-lines, so it may not work with all regex parsers.

/\<!\s*--(.*?)(--\s*\>)/m

Examples in Ruby IRB:
irb(main):029:0> html = <<-EOL
irb(main):030:0" <!--  First  Comment   --
irb(main):031:0"       --> Second Comment <!--
irb(main):032:0"       --  Third  Comment   -->
irb(main):033:0" EOL
=> "<!--  First  Comment   --\n      --> Second Comment <!--\n      --  Third  Comment   -->\n"
irb(main):075:0> m = html.match(/\<!\s*--(.*?)(--\s*\>)/m)
=> #<MatchData:0x15915a4>
irb(main):076:0> m[0]
=> "<!--  First  Comment   --\n      -->"
irb(main):077:0> m[1]
=> "  First  Comment   --\n      "

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS