my $regex = '\A' . ('[^x]*x' x $n) . '[^x]*'; $foo =~ m{ ($regex) }xms; # PBP orthodoxy :)