import re
regex = re.compile(r"(^( +|)\[(?<name>[^#;\r\n]+)\])|(^( +|)(?<key>[^\[\]\r\n=#;]+)( |)=( |)(?<value>[^#;\\\r\n]*(?:\\.[^#;\\\r\n]*)*))|((#|;)(?<comm>.+)$)", flags=re.MULTILINE)
test_str = (";An orphan comment at the top of the file\n"
" #Another orphan comment\n\n"
"#Comment above a group\n"
"[Group1] #Group comment 1\n"
"Key1=Value1#Comment 1\n"
"Key2=Value 2\n"
"Key 3=Value 3\n"
" Key 4=Value4\n"
"Key5=Value \\#5;Comment 2\n\n"
";Another comment above a group\n"
" [Group 2] ;Group comment 2\n"
"Key1 = Value1 #Comment 3\n"
"Key2 = Value 2\n"
"Key 3 = Value 3\n"
"Key 4 = Value4\n"
" Key 5 = Value\\;5 ;Comment 4")
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