@matches = ($_ =~ /A(BC|)D/g) if(@matches != 0){ foreach(@matches){ print "$_.\n"; } } } the code prints 1 BC 1