import re
regex = re.compile(r"((^|\s)#(.*)$)|(^\n)|(\n(\s|)+#(.*)$)|([\n\s]+#.*)|([\n\s]{2,}$)", flags=re.MULTILINE)
test_str = ("#This RegEx removes inline comments and blank lines in python code!\n\n"
"# This will save you tokens and time when using GPT to help code and debug.\n\n\n"
"import requests\n"
"import os\n\n\n"
"#Define vars\n"
"def add(a, b):\n"
" return a + b\n"
"# print results\n"
"result = add(2, 3)\n"
"print(result) # Output: 5\n"
"print(\"Complete\")\n\n\n")
subst = ""
result = regex.sub(subst, test_str)
if result:
print(result)
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Python, please visit: https://docs.python.org/3/library/re.html