s/<~( ( [^~]* # match anything but a ~ (~(?!>))? # match a ~ NOT followed by a > # the non > char is not captured so # it is still available for matching )* # match this sequence again )/expand($1)/x;