import re
regex = re.compile(r"^(?<rank>(?:(?:[ \t]|^)[a-z]+)+?)(?!(?:[ \t][a-z.]+){4,}$)[ \t](?<first>[a-z]+)[ \t](?:(?<middle>[a-z.]+)[ \t])?(?<last>[a-z]+)$", flags=re.IGNORECASE | re.MULTILINE)
test_str = ("High Sheriff John Caldwell. Cook\n"
"Deputy Sheriff John A. Gooch\n"
"Marshall Robert Forsyth\n"
"Constable Darius Quimby\n\n"
"#Exception (when you have First, Last and more than 1 word for the rank):\n"
"Deputy Sheriff John Gooch\n\n"
"#In the last example you have to define a list of rank prefixes which mean that there's another word definitely going after it and capture it greedy or with possessive quantifier. E.g.: Deputy,High.")
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