There are several ways to do this better than what I'm going to suggest to you (you could use some dedicated library, like flex&Bison, or using define at compilation time, if it is your case). I'm writing this answer only for fun. This is the python code:
import re
IF_REGEX = re.compile(r'^s*#if defines*((.*))s*$')
ELSE_REGEX = re.compile(r'^s*#elses*$')
ENDIF_REGEX = re.compile(r'^s*#endifs*$')
def parse_text(filepath, conditions):
# Read file
with open(filepath, 'r') as f:
lines = f.readlines()
parsed_text = []
keeps = []
for line in lines:
m = IF_REGEX.match(line)
if m is not None:
keeps.append(m.groups()[0] in conditions)
elif ELSE_REGEX.match(line):
keeps[-1] = not keeps[-1]
elif ENDIF_REGEX.match(line):
keeps = keeps[:-1]
elif all(keeps):
parsed_text.append(line)
# Join lines back together
return ''.join(parsed_text)
Suppose that input_code.c
is the file with the C code in your question, then:
parse_text('input_code.c', conditions=['sweety is coming'])
will produce:
#include <stdio.h>
#include <main.h>
do somethinhg
if(great)
do something something
you can stop the Program
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…