import re
regex = re.compile(r"(^(?:\d+_){4})(card\d+)_(port\d+)", flags=re.MULTILINE)
test_str = ("192_168_10_2_card02_port01_other_text_with_card_or_port\n"
"10_22_1_200_card4_port5_another_string_with_port_or_card\n"
"something_else_with_card_or_port_in_it\n\n\n"
"And in a second call, I'd like to match a different word in these strings.\n"
"192_168_10_2_card02_port01_other_text_with_card_or_port\n"
"10_22_1_200_card4_port5_another_string_with_port_or_card\n"
"something_else_with_card_or_port_in_it")
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