# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"^(?:([^:\n]+):)?([^(\n]+)(.+)?"
test_str = ("Misc Parts\n"
"Retail:Oil-20W50 Phillips (Aviation Oil, 20W50 12/1 QT (sold by the case))\n"
"Discount 10% AA (10% Discount)\n"
"Shipping & Handling (Shipping & Handling)\n"
"Tailwheel Parts:A4050 (Cone Bearing)\n"
"Tailwheel Parts:A4138 (Bearing Race)\n"
"Shipping & Handling (Shipping & Handling)\n"
"Tailwheel Parts:ABI-3234-00 (Thrust Plate Assy.)\n"
"Shipping & Handling (Shipping & Handling)\n"
"Shipping & Handling (Shipping & Handling)\n"
"Shipping & Handling (Shipping & Handling)\n"
"Tailwheel Parts-Assemblies:ABI-3235-02 (Upper Dust Cover Straight Arm )\n"
"Tailwheel Parts:ABI-3206-00 (Thrust Washer)\n"
"Tailwheel Parts:ABI-3233-00 (Compression Spring)\n"
"Tailwheel Parts:ABI-3205-00 (Bushing)\n"
"Tailwheel Parts:ABI-3219-02 (Pawl (Long))\n"
"Shipping & Handling (Shipping & Handling)\n"
"Shipping & Handling (Shipping & Handling)\n"
"This should match as part number\n"
"Vendor:Part Number\n"
"Vendor:Part Number (Description)\n"
"Hello (World:Meow)")
matches = re.finditer(regex, test_str, re.MULTILINE)
for matchNum, match in enumerate(matches, start=1):
print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
for groupNum in range(0, len(match.groups())):
groupNum = groupNum + 1
print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
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