$_ = "04abcdefgh"; my $result; if (/ (\d\d) /gx) { $result .= $&; my $count = 0 + $1; if (/ \G .{$count} /x) { $result .= $&; } else { $result = undef } } dd $result; #-> "04abcd"