# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"(.+> )?([^>]+)(.+)? > \2(.+)?"
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"
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
if result:
print (result)
# 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