comment_remover.py 592 B

12345678910111213141516171819202122
  1. """Removes C/C++ style comments from text.
  2. Gratefully adapted from https://stackoverflow.com/a/241506
  3. """
  4. import re
  5. from functools import lru_cache
  6. comment_pattern = re.compile(r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\.|[^\\"])*"', re.DOTALL | re.MULTILINE)
  7. def _comment_stripper(match):
  8. """Removes C/C++ style comments from a regex match.
  9. """
  10. s = match.group(0)
  11. return ' ' if s.startswith('/') else s
  12. @lru_cache(maxsize=0)
  13. def comment_remover(text):
  14. """Remove C/C++ style comments from text.
  15. """
  16. return re.sub(comment_pattern, _comment_stripper, text)