$ perl -le '$str = q{AND (random text) OR (more random text) AND (yet (more))};print "$1: $2" while ($str =~ /(AND|OR)\s+(.+?)(?=AND|OR|$)/g)' AND: (random text) OR: (more random text) AND: (yet (more))