import re
regex = re.compile(r"(err\s*?\d{1})|[^\d]\s+(\d{3})(?:$|\s+(?!\d))", flags=re.MULTILINE | re.IGNORECASE)
test_str = ("The below items should match:\n"
"-----------------------------\n"
"123\n"
"456 123\n"
"123 324 324\n"
"Match the number in this sentence 123 as well\n"
"999\n\n"
"The below items should NOT match:\n"
"---------------------------------\n"
"1234\n"
"12345\n"
"123456\n"
"1234567\n\n"
"£123\n"
"$456\n\n"
"Err404\n"
"ERR404\n"
"err404\n"
"Err 404\n"
"ERR 404\n"
"err 404\n\n"
"there is err 404 on page\n"
"this err 1232222222222 as well\n\n"
"a string 12323 like this\n"
"asd\n"
"4444333322221111\n"
"4444 3333 2222 1111\n"
"Err123\n\n"
"02012341234\n"
"920 1234 1234")
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