I don't know how to do so with a regex; perhaps index might help you (but in a complicated way, I'm afraid), e.g
#!perl -w
use strict;
my $searchString = '$a';
my $replaceString = '$b';
my $string = '$a($a hi) $a (($a))$a';
# get positions of chars to care about
my @aPos = &GetCharPositions($string, $searchString);;
my @lparants = &GetCharPositions($string, '(');
my @rparants = &GetCharPositions($string, ')');
print "String: $string\n";
print "LeftP: @lparants\n";
print "RightP: @rparants\n";
die "Error: non equal paranthesis found\n" if ($#lparants != $#rparant
+s);
print "@aPos\n";
# filter stuff between parantheses
foreach my $i (0..$#lparants){
@aPos = grep { $_ < $lparants[$i] or $_ > $rparants[$i] } @aPos;
print "AP: @aPos\n";
}
# do replacement of stuff still in @aPos
foreach (@aPos){
substr($string, $_, length($searchString)) = $replaceString;
print "S: $string\n";
}
# ------------------------------------------------------------
sub GetCharPositions {
my ($string, $subString) = @_;
my @list = ();
my $startPos = -1;
my $pos;
while ( defined ($pos = index($string, $subString, $startPos+1))){
last if $pos == -1;
$startPos = $pos;
push (@list, $pos);
}
return (@list);
} # GetCharPositions
# ----------------------------------------------------
Output:
C:\TEMP\test>parenReplace.pl
String: $a($a hi) $a (($a))$a
LeftP: 2 13 14
RightP: 8 17 18
0 3 10 15 19
AP: 0 10 15 19
AP: 0 10 19
AP: 0 10 19
S: $b($a hi) $a (($a))$a
S: $b($a hi) $b (($a))$a
S: $b($a hi) $b (($a))$b
I haven't thoroughly tested this code, and can't tell if it is correct under each circumstances...
But I'm looking forward getting some better solutions :-)
Best regards,
perl -le "s==*F=e=>y~\*martinF~stronat~=>s~[^\w]~~g=>chop,print" |