import re
regex = re.compile(r"^step\s*(\d+)\s*(.*?)\s*(?=^step\s*\d|\Z)", flags=re.MULTILINE | re.DOTALL)
test_str = ("This is the first line of the file.\n"
"here we tell you to make a tea.\n\n"
"step 1\n\n"
"Pour more than enough water for a cup of tea into a regular pot, and bring it to a boil.\n\n"
"step \n"
"2\n\n"
" This will prevent the steeping water from dropping in temperature as soon as it is poured in.\n\n"
"step 3 \n\n\n"
"When using tea bags, the measuring has already been done for you - generally it's one tea bag per cup.")
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