import re
regex = re.compile(r"^[ \t]*\*[A-Z]{2,3},\s*(?:[ART]|RSS?)\.?[\n\r](?:(?!^[ \t]*\*[A-Z]{2,3},\s*(?:[ART]|RSS?)\.?[\n\r])[\s\S])+", flags=re.MULTILINE)
test_str = ("*GW, A\n"
"This is my very first line. The asterics defines a new block, followed by the initials (2-3 chars), a comma, a (possible) space and a code that could be A, R, T, RS or RSS. Followed by that is an optional dot. Linebreak afterwards, where the text comes.\n\n"
" *JP, R.\n"
" New block here, as the line (kind of) starts with an asterics. Indentations with 4 spaces or a tab means that it is a second level thing only, that does not need to be stripped away necessarily.\n\n"
" But as you can see, a block can be devided into several\n"
" lines, \n\n"
" even with multiple lines.\n\n"
" *GML, T.\n"
" And so we continue...\n\n"
" Let's just make sure that a line can start with an\n"
" *asterics, without breaking the whole thing.\n"
" *GW, RS\n"
" Yet another block here.\n\n"
" *GW, RSS.\n"
" And a very final one.\n\n"
" Spread over several lines.\n\n"
"*TA, RS.\n"
"First level all of a sudden again.\n")
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