If I have understood correctly what you require, use the "word boundary" asserstion (\b), see perlre.
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
(?<! [A-Za-z_] ) # Match at a point not preceded by
# letters or underscore
(?= [A-Za-z_] ) # And which is followed by letters
# or underscore
(?! $rxExcl ) # But not followed by any our terms
# to exclude
}g;
substr $str, $_, 0, qq{$path.} for reverse @posns;
say $str;
The output.
(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
I hope this is what you want.