Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Problem with nested StringReplace[]

0 views
Skip to first unread message

dnquark

unread,
Jul 2, 2009, 7:13:59 AM7/2/09
to
I am trying to match a substring using a regular expression, and right
away apply some replacement rules to that substring. Suppose I want
to match a substring "bar" and right away replace it using the rule
{"bar" -> "baz"}. The following doesn't work: expected: "baz",
actual: "bar"
StringReplace[
"foobar",
RegularExpression["foo(bar)"] ->
StringReplace["$1", {"bar" -> "baz"}]]

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?..

pfalloon

unread,
Jul 9, 2009, 1:57:50 AM7/9/09
to

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.

0 new messages