use 5.010; # for (?|pattern) and (*FAIL) use warnings FATAL => 'all' ; use strict; # factored regexes my $r_s_g = qr{ (?i) (?> \b (?: revenues? | sales | growth ) \b) }xms; my $c_fe = qr{ (?i) (?> \b (?: currency | foreign \W exchange) \b) }xms; my $word = qr{ \b \w+ \W+ (?: \b | \Z) }xms; my $max_between = 4; my $near = qr{ (?:$word){0,$max_between}? }xms; # the test text my $s = <[0]' ... '$_->[1]' \n} for @matches; print qq{\n}; # just count matches our $n_matches; $s =~ m{ (?= (?| $r_s_g \W+ $near $c_fe | $c_fe \W+ $near $r_s_g) (?{ ++$n_matches }) (*FAIL) ) }xmsg; print qq{$n_matches matches \n}; #### [[Currency revenue and sales growth in foreign exchange Sales and Revenues ]] 'Currency' ... 'revenue' 'Currency' ... 'sales' 'Currency' ... 'growth' 'revenue' ... 'foreign exchange' 'sales' ... 'foreign exchange' 'growth' ... 'foreign exchange' 'foreign exchange' ... 'Sales' 'foreign exchange' ... 'Revenues' 8 matches