$_ = 'ju[color=1]s[/color]t a sam[color=2]p[/color]le'; my $brackets = qr(\[[^\]]*\]); # text enclosed in brackets my $char = qr([^\[\]\s]); # not spaces or brackets s{ ( # group to $1 (?: $char # a char (?:$brackets*) # followed by any number of brackets ) {3} # 3 times ) (?:$brackets*) # followed by any number of brackets (?= # looking forward to ensure that $char # we have at least one char [^\[\]]* # and we are not inside of a brackets (?: \[ | \z ) ) } {$1-}gx; print;