comment_re = re.compile(
    '(^)?[^\\S\\n]*/(?:\\*(.*?)\\*/[^\\S\\n]*|/[^\\n]*)($)?', re.DOTALL |
    re.MULTILINE)

def comment_replacer(match):
    start, mid, end = match.group(1, 2, 3)
if mid is None:
    return ''
elif start is not None or end is not None:
    return ''
elif '\n' in mid:
    return '\n'
else:
    return ' '

def remove_comments(text):
    return comment_re.sub(comment_replacer, text)
Python regex question: stripping multi-line comments but maintaining a line break