Stack Exchange network consists of 183 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.
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
$\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$
$\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$
$\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$
replaceFirst[expr_, old_, new_] := ReplacePart[expr, Position[expr, old][[1]] -> new]
$\endgroup$replacement = "A"; {"a", "b", "a", "c"} /. x : "a" :> With[{res = replacement}, replacement = x; res]
$\endgroup$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}, doReplaceList[{1,1,1},{a___,1,b___}:> {a,2,b},1]
. Result :{{2, 1, 1}}
$\endgroup$