Skip to content

Instantly share code, notes, and snippets.

@east825
Created September 20, 2012 15:31
Show Gist options
  • Save east825/3756630 to your computer and use it in GitHub Desktop.
Save east825/3756630 to your computer and use it in GitHub Desktop.
function to remove multiline commentaries from C code
import re
strings_literals = re.compile(r'"(?:\\"|.)*?"')
commentaries = re.compile(r'/\*.*?\*/', re.DOTALL)
placeholder = '<{}>'
def cut_commentaries(s):
strings = []
def insert_placeholder(m):
print(m.group(0))
strings.append(m.group(0))
return placeholder
def replace_back(m):
return strings.pop()
updated = strings_literals.sub(insert_placeholder, s)
strings.reverse()
updated = re.sub(commentaries, '', updated)
updated = re.sub(placeholder, replace_back, updated)
return updated
if __name__ == '__main__':
ex1 = """
some "co\\"de":where /* sjdfljsf */ /*foobar*/ /*or
not foobar */ and other "then"
"""
print(cut_commentaries(ex1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment