chomp( (undef, $_, undef, @words) = <> ); %restore_case = map { lc, $_ } @words; $list = join '|', map { scalar reverse lc } @words; m/^ (?: ($list | $ | (?{ pop @submatches }) (?!) ) (?{ push @submatches, $^N }) )+ $/x; pop @submatches; print join ' ', map { $restore_case{ scalar reverse } } @submatches