$cities = "Here/There/Everywhere/There/Again/Here/Too"; $cities =~ s{ ([^/]+) # non-slashes (the city): \1 / # a / (?= # look ahead for:... (?: # group (not capture) [^/]* / # city and / )*? # 0 or more times, non-greedily \1 # is the city here again? (?: /|$ ) # a / or end-of-string ) } {}gx;