2
$\begingroup$

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

$\endgroup$
5
  • $\begingroup$ replaceFirst[expr_, old_, new_] := ReplacePart[expr, Position[expr, old][[1]] -> new] $\endgroup$
    – Bob Hanlon
    Commented May 5, 2017 at 18:51
  • $\begingroup$ Or, much more hacky, replacement = "A"; {"a", "b", "a", "c"} /. x : "a" :> With[{res = replacement}, replacement = x; res] $\endgroup$
    – Jason B.
    Commented May 5, 2017 at 18:53
  • $\begingroup$ 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}} $\endgroup$
    – andre314
    Commented May 5, 2017 at 19:22
  • $\begingroup$ 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. $\endgroup$
    – mikado
    Commented May 5, 2017 at 20:18
  • $\begingroup$ 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. $\endgroup$ Commented May 7, 2017 at 9:33

0

Browse other questions tagged or ask your own question.