2
$\begingroup$

I want to replace numbers in a string based on a numeric condition. Let us suppose the following string

"xxxx250 123|1,4|0,5|1,17|0,55|1,111|0"

I want to replace those numbers that are part of a pattern "X|1“ and where X>50. Hence in my case, this would be "123" and "55". Then, I want to replace "123|1" and "55|1“ by "127|0" and "166|0“, hence by the sum of 123 or 55 and the next number before the next |0, hence 4 or 111 and the "|1" by "|0". The result should be

"xxxx250 127|0,5|1,17|0,166|0"

Any ideas?

$\endgroup$
1
  • $\begingroup$ The pattern X|1 will never happen twice without some X|0 in between? $\endgroup$
    – Coolwater
    Commented Jan 27, 2021 at 13:52

1 Answer 1

1
$\begingroup$
string = "xxxx250 123|1,4|0,5|1,17|0,55|1,111|0";

StringReplace[string, n1 : NumberString ~~ "|1" ~~ "," ~~ n2 : NumberString ~~ "|0" /; 
   ToExpression[n1] > 50 :> ToString[ToExpression[n1] + ToExpression[n2]] <> "|0"]
"xxxx250 127|0,5|1,17|0,166|0"
$\endgroup$
2
  • $\begingroup$ THANKS A LOT. It works. $\endgroup$ Commented Jan 27, 2021 at 11:37
  • $\begingroup$ @dirksaller, my pleasure. Thank you for the accept and Welcome to mma.se. $\endgroup$
    – kglr
    Commented Jan 27, 2021 at 11:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.