use strict; use warnings; use 5.014; my $path = q{XX.YY.ZZ}; my $str = q{(ABC | (~dEf & hI_J)) & ~LMn if ~xYz}; # Make a compiled regex of an alternation of the terms to exclude. # my $rxExcl = do { my @excl = qw{ if else 1'b0 }; local $" = q{|}; qr{(?:@excl)}; }; 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.LMn if ~XX.YY.ZZ.xYz