import re
regex = re.compile(r"^([^\"\s=]+)=('{[\s\S]*?\n}'|.*)", flags=re.MULTILINE)
test_str = ("# IN TOTAL, THE REGEX SHOULD MATCH 4 KEY-VALUE PAIRS FROM THIS FILE.\n"
"KEY1='{\n"
" \"string\" = {\n"
" \"key\" = \"value\",\n"
" \"key\" = \"value\"\n"
" },\n"
" \"string\" = {\n"
" \"key\" = \"value\",\n"
" \"key\" = \"value\"\n"
" }\n"
"}'\n\n"
"# DO NOT MATCH ON COMMENTS, EVEN THOSE WITH X=Y in them.\n\n"
"# ALSO IGNORE THIS COMMENT, AND NEW LINES AROUND.\n\n"
"KEY2=SOME_TEXT\n"
"KEY3=\"SOME_MORE_TEXT\"\n"
"KEY4='EVEN_MORE_TEXT'")
subst = "PREFIX_\\1: \\2"
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