import re
regex = re.compile(r"^(.*):\s*Bus Number: Departure\s*\nBus code:\s*([^ ]+)\s([^ ]+)\s([^\n]+)[ \t]*(?:\n|$)((?:[^\n]+\n)+)?", flags=re.MULTILINE)
test_str = ("KPN_Sleeper: Bus Number: Departure \n"
"Bus code: Kpn-866489 KA-01-7233 Bangalore dfdf\n"
"AC Sleeper/56 Seats\n"
"24 Seats booked \n\n"
"SRS: Bus Number: Departure \n"
"Bus code: SRS-5858 KA-31-5985 Bangalore dfdf dfd\n\n\n"
"SAM: Bus Number: Departure \n"
"Bus code: SAM-0077 TN-23-0777 Chennai ")
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