foreach $arr ("foo abc12345 def12345678 bar") { if (($arr =~ /(\w*)(abc)(\d{5})/) && ($arr =~ / (\w*)(def)(\d{8})/)) { print $3; # "12345678" } }