0

I am reading the C file using .readlines() to get all the individual lines of a C code file as elements of a list. If any of the list elements (i.e. C code line) a part of a multiline comment it needs to be replaced by ''(i.e. delete it but it will occupy the corresponding index of the list) so that indexing of further lines is not altered. Please check my code for details.

import re

#open and read sample.c so that code lines of sample.c are the element of list 'flist'

with open('sample.c',mode='r') as myfile: 
    flist = myfile.readlines() 


pattern1 = re.compile(r'\/{2}.*')         # to match //
pattern2 = re.compile('\/\*.*\*\/')       # to match /*......*/ in a single line or element of flist
pattern3 = re.compile('\/\*')             # to match /*
pattern4 = re.compile('\*\/')             # to match */ 

# to delete comments present in a single code line or can say in an individual element of 'flist', it's working fine.

for index,line in enumerate(flist):
    if pattern2.search(line):
       flist[index] = pattern2.sub("",line)
    if pattern1.search(line):
        flist[index] = pattern1.sub("",line)

# to delete comment starting in one line and ending in the subsequent line, **this following part is not working** 

cmnt_e = True
cmnt_s = False

for index,line in enumerate(flist):
    if pattern3.search(line) and cmnt_e == True:
        cmnt_s = True
        cmnt_e = False
    if pattern3.search(line) and cmnt_s == True:
        cmnt_e = True
        cmnt_s = False
    if cmnt_s == True and cmnt_e == False:
        flist[index] = ''
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563

1 Answers1

0

I'm not looking too much in the details, but you are using pattern3 for both start and end of comments. I guess it should be something like

    if pattern3.search(line) and cmnt_e == True:
        cmnt_s = True
        cmnt_e = False
    if pattern4.search(line) and cmnt_s == True:
        cmnt_e = True
        cmnt_s = False

I would also be wary of strange patterns like this one (yes, I use this sometime for experimental stuffs, you just flip the first slash to flip the active code) :

//*
ACTIVE_CODE
/*/
INACTIVE_CODE
//*/
Paul Bombarde
  • 311
  • 2
  • 7