#!/usr/bin/perl use warnings; use strict; for my $string (qw(ab1b2b3b4d ab5b6b7d ab8b9d abxd ad)) { my @two; my @matches = $string =~ /(a) (?:(b.)(?{ push @two, $2 }))+ (d)/x; @matches and splice @matches, 1, 1, @two; print "@matches\n"; }