1 while s{ (/|^) # add: capture slash or start of string: $1 ([^/]+) # non-slashes (the city): \2 / # a / (?= # look ahead for:... (?: # group (not capture) [^/]* / # city and / )*? # 0 or more times, non-greedily \2 # is the city here again? (?: /|$ ) # a / or end-of-string ) } {$1}gx; # add: replacement