2

After searching quite thoroughly, I haven't been able to find a good answer... I'm looking to find an option for Replace to stop after it encounters the first rule which applies to some expression. Thanks

  • `replaceFirst[expr_, old_, new_] :=

    ReplacePart[expr, Position[expr, old][[1]] -> new]`

    – Bob Hanlon May 05 '17 at 18:51
  • Or, much more hacky, replacement = "A"; {"a", "b", "a", "c"} /. x : "a" :> With[{res = replacement}, replacement = x; res] – Jason B. May 05 '17 at 18:53
  • In some cases ReplaceList[exp,rule,1]can do the job. The problem is that the rule is only applied at level 0 of exp. Example : to replace 1 by 2 only one time in {1,1,1}, do ReplaceList[{1,1,1},{a___,1,b___}:> {a,2,b},1]. Result : {{2, 1, 1}} – andre314 May 05 '17 at 19:22
  • I'm not sure that this is a duplicate of the question indicated. If it isn't, I suggest editing the question to give 1) an example input 2) an example set of rules and 3) the output desired. – mikado May 05 '17 at 20:18
  • Thanks for all the answers! I'll try them out,
    @mikado, the question indicated was exactly what I was looking for, probably I haven't been clear enough.
    – Gaby Fleurov May 07 '17 at 09:33

0 Answers0