my $format = ...; my $printfStr; my $regexStr; my $paramCount; while ($format) { my ($chunk) = $format =~ s/^(.*?|\[.*?])(?:\[|$)//g; if ($chunk =~ /^\[int]/) {# match an int $printfStr .= "%d"; $regexStr .= "(\\d+)"; ++$paramCount; } elsif ... else {# match the text $printfStr .= $chunk; $regexStr .= "\Q$chunk\E"; } }