import re
regex = re.compile(r"(.+> )?([^>]+)(.+)? > \2(.+)?", flags=re.MULTILINE)
test_str = (" Boating > Anchoring > Accessories > Anchors/Chain/Rope\n"
" Boating > Safety > Fire & Vapor Detectors > Fume Detectors\n"
" Clothing > Sportswear > Shirts > T-Shirts Polo\n"
" Gear > Knives & Tools > Knives Fixed Blade > Fixed Blade Knives\n"
" Hunting > Tree Stands > Accessories > Tree Stands and Accessories\n"
" Optics > Rings & Mounts > Scope Rings > Rings & Accessories\n"
" Gear > Climbing & Rappelling > Rope Cord Webbing > Rope Cord & Webbing\n\n"
" Fishing > Rod & Reel Combos > Rod & Reel Combos > Types of Fishing > Fishing Gear - Kids > Offshore Fishing Gear > Saltwater Fly Fishing Gear > Trolling Fishing Gear\n\n"
" Fishing > Lures > Hard Baits > Lures Hard Baits\n")
subst = "\\1\\2\\3\\4"
result = regex.sub(subst, test_str)
if result:
print(result)
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