my $s = ' ABC: 123 xyz: 100 def: YYY aaa: ZZZ'; my $count = my @order = $s =~ /:/sg; $regex = '(\w+:\s\w+)'.('\s+(\1)' x --$count); print $regex; if ($s =~ /$regex/){ print "regex works"; }