Skip to content

Instantly share code, notes, and snippets.

@javiermon
Created March 21, 2018 00:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save javiermon/3b26d4d08990e40301d2550bd6acc35c to your computer and use it in GitHub Desktop.
Save javiermon/3b26d4d08990e40301d2550bd6acc35c to your computer and use it in GitHub Desktop.
#!/usr/bin/python
# https://www.saltycrane.com/blog/2007/11/remove-c-comments-python/
import re
import sys
def remove_comments(text):
""" remove c-style comments.
text: blob of text with comments (can include newlines)
returns: text with comments removed
"""
pattern = r"""
## --------- COMMENT ---------
/\* ## Start of /* ... */ comment
[^*]*\*+ ## Non-* followed by 1-or-more *'s
( ##
[^/*][^*]*\*+ ##
)* ## 0-or-more things which don't start with /
## but do end with '*'
/ ## End of /* ... */ comment
| ## -OR- various things which aren't comments:
( ##
## ------ " ... " STRING ------
" ## Start of " ... " string
( ##
\\. ## Escaped char
| ## -OR-
[^"\\] ## Non "\ characters
)* ##
" ## End of " ... " string
| ## -OR-
##
## ------ ' ... ' STRING ------
' ## Start of ' ... ' string
( ##
\\. ## Escaped char
| ## -OR-
[^'\\] ## Non '\ characters
)* ##
' ## End of ' ... ' string
| ## -OR-
##
## ------ ANYTHING ELSE -------
. ## Anything other char
[^/"'\\]* ## Chars which doesn't start a comment, string
) ## or escape
"""
regex = re.compile(pattern, re.VERBOSE|re.MULTILINE|re.DOTALL)
noncomments = [m.group(2) for m in regex.finditer(text) if m.group(2)]
return "".join(noncomments)
if __name__ == '__main__':
filename = sys.argv[1]
with open(filename, "r") as commented:
code_w_comments = commented.read()
code_wo_comments = remove_comments(code_w_comments)
with open(filename, "w") as uncommented:
uncommented.write(code_wo_comments)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment