http://www.perlmonks.org?node_id=763980


in reply to Regexp matching words, not doing what I expect

You should consider ditching the regex approach and using a module: Text::Ngrams looks like the right one for you (not to be confused with Text::Ngram -- note the "singular" -- which only works on character ngrams, not word ngrams).

If you have some strange compulsion not to use a module, you should still consider ditching the regex -- split the string into an array of words and use a for loop to output your word pairs:

my @words = split " ", $text; print "$words[$_-1] $words[$_]\n" for ( 1 .. $#words );
(updated to fix bone-headed error in for loop)