import re
regex = re.compile(r"(?P<oxford_comma>,)(?=\s+(and|or))")
test_str = ("The canning, processing, preserving, freezing, drying, marketing, storing, packing for shipment or distribution of:\n\n"
"Agricultural produce;\n"
"Meat and fish product; and\n"
"Perishable foods\n\n"
"The canning, processing, preserving, freezing, drying, marketing, storing, packing for shipment, or distribution of:\n\n"
"While Sean was waiting for Kyle to pick up Chinese for dinner, he scraped the paint off the bathroom door frame, alphabetized his books by main character’s first name, and successfully startled the neighbor’s boxer twice.\n\n"
"The Oxford comma makes these sentences carry entirely different meanings:\n"
"Amanda found herself in the Winnebago with her ex-boyfriend, an herbalist and a pet detective.\n"
"Amanda found herself in the Winnebago with her ex-boyfriend, an herbalist, and a pet detective.\n")
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