use strict; use warnings; use 5.014; my $path = q{XX.YY.ZZ}; my $str = q{(ABC | (~dEf & hI_J & endxxx)) & ~LMn if ~xYz end}; # Make a compiled regex of an alternation of the terms to exclude. # my $rxExcl = do { my @excl = qw{ if else 1'b0 end }; local $" = q{|}; qr{(?x) (?: @excl ) \b}; }; my @posns; push @posns, pos $str while $str =~ m{(?x) # Use extended regex syntax (?## (XX.YY.ZZ.ABC | (~XX.YY.ZZ.dEf & XX.YY.ZZ.hI_J & XX.YY.ZZ.endxxx)) & ~XX.YY.ZZ.LMn if ~XX.YY.ZZ.xYz end