Replacing the first rule with a delayed rule (:>) produces the
expected result, but I cannot use the delayed rule -- it produces side
effects in my code. Is there a reason that the regular rule ->
doesn't work in this case?..
The problem with using Rule (->) is that the right hand side is
evaluated immediately. In this case,
In[609]:= StringReplace["$1", {"bar" -> "baz"}]
Out[609]= "$1"
So all you're left with is "$1", which will return "bar".
This is actually quite a typical example of where one would normally
use RuleDelayed (:>), so maybe it would be worth looking at the "side
effects" which it is producing and see whether these can be avoided?
Cheers,
Peter.