I would like to replace the occurrence of "a(x)" and "b(x)" in a list with "a(x-na)" and "b(x-nb)" where na and nb are the number of a's and b's respectively. x-na should be evaluated. I've tried

list = {"a(1)", "a(2)", "a(3)", "b(4)", "b(5)", "b(6)"}
na = Total[StringCount[list, "a"]]
nb = Total[StringCount[list, "b"]]
StringReplace[list, {"a(" ~~ n___ ~~ ")" -> 
   "a(" <> ToString[n - na] <> ")"}]
{"a(-3 + n)", "a(-3 + n)", "a(-3 + n)", "b(4)", "b(5)", "b(6)"} 

But as you can see it is not working as intended.

Can you help me please?


1 Answer 1

 {h_ ~~ "(" ~~ n_ ~~ ")" :> 
   h <> "(" <> ToString[ToExpression[n] - Symbol["n" <> h]] <> ")"
 {"a(-2)", "a(-1)", "a(0)", "b(1)", "b(2)", "b(3)"} 

Tell me if anything is not clear.

And some fun:

  Map[ToString@ToString[#, TraditionalForm] &],
  # /. h_[n_Integer] :> h[n - CountsBy[#, Head][h]] &,
  Map[ToExpression[#, TraditionalForm] &]

  ]@{"a(1)", "a(2)", "a(3)", "b(4)", "b(5)", "b(6)"}
{"a(-2)", "a(-1)", "a(0)", "b(1)", "b(2)", "b(3)"} 
  • $\begingroup$ That is good. You did more than I requested since I can do two StringReplace for a and b separately. Thanks! $\endgroup$
    – Fabio
    Commented Dec 3, 2015 at 17:52

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.