MathGroup Archive 2009

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Problem with nested StringReplace[]

  • To: mathgroup at smc.vnet.net
  • Subject: [mg101537] Re: Problem with nested StringReplace[]
  • From: pfalloon <pfalloon at gmail.com>
  • Date: Thu, 9 Jul 2009 01:59:52 -0400 (EDT)
  • References: <h2i4pn$939$1@smc.vnet.net>

On Jul 2, 9:13 pm, dnquark <dnqu... at gmail.com> wrote:
> 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?..

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.


  • Prev by Date: Re: logical simplification problem
  • Next by Date: Re: Jens-Peer Kuska passed away
  • Previous by thread: Re: 2dFFT & image processing
  • Next by thread: Add syntax highlighting to own command