What's a good way to remove all text from a file which lies between /* */
and #if 0
and corresponding #endif
? I want to strip these parts from C headers. This is the code I have so far:
For line in file:if def0Encountered == 0: if Line.strip().startswith('#if 0') == True: Def0StartsAt = Line.find('#if 0') def0Encountered = 1 if Line.find('#endif')!= -1: def0Encountered = 0 Def0EndsAt = Line.find('endif') Line = Line[0:Def0StartsAt] + Line[Def0EndsAt + 2 : ] List = Line.split()
You could use a regular expression to replace the parts of the file you don't want with the empty string (Note, this is very basic, it won't work e.g. for nested macros):
#!/usr/bin/env pythonimport re# uncomment/comment for test with a real file ...
# header = open('mycfile.c', 'r').read()
header = """#if 0whatever(necessary)and maybe more#endif/* * This is an original style comment**/int main (int argc, char const *argv[])
{/* code */return 0;
}"""p_macro = re.compile("#if.*?#endif", re.DOTALL)
p_comment = re.compile("/\*.*?\*/", re.DOTALL)# Example ...
# print re.sub(p_macro, '', header)
# print re.sub(p_comment, '', header)