import re
regex = re.compile(r"(?m)^(?:--|[[:space:]]+).+")
test_str = ("-- Query taken from:\n"
"-- https://stackoverflow.com/a/12467388/1655567\n"
"SELECT country.name as country, country.headofstate\n"
"from country\n"
" -- Worst place to add comment ever\n"
" -- Here is even uglier\n"
"inner join city on city.id = country.capital\n"
"where city.population > 100000\n"
"-- this comment makes no sense here and would break sql parser buyt hey\n"
"and country.headofstate like 'A%'\n"
"-- WOW!")
matches = regex.finditer(test_str)
for match_num, match in enumerate(matches, start=1):
print(f"Match {match_num} was found at {match.start()}-{match.end()}: {match.group()}")
for group_num, group in enumerate(match.groups(), start=1):
print(f"Group {group_num} found at {match.start(group_num)}-{match.end(group_num)}: {group}")
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