3
$\begingroup$
StringReplace["item_10", "item_" ~~ x__ -> x + 1]

returns "1+10"

How can I force it to evaluate to 11?

$\endgroup$
  • $\begingroup$ Welcome to Mathematica.SE! I suggest that: 1) You take the introductory Tour now! 2) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! 3) As you receive help, try to give it too, by answering questions in your area of expertise. $\endgroup$ – bbgodfrey Mar 4 '15 at 19:33
  • 1
    $\begingroup$ To 11 or "11"? $\endgroup$ – Kuba Mar 4 '15 at 19:34
  • $\begingroup$ Related: (4230) $\endgroup$ – Mr.Wizard Mar 4 '15 at 19:38
3
$\begingroup$

This returns "11":

StringReplace["item_10",  "item_" ~~ x__ :> ToString[ToExpression[x] + 1] ]
StringReplace["item_10",  "item_" ~~ x__ :> ToString[ToExpression[x <> "+1"]] ]

This 11:

StringCases["item_10", "item_" ~~ x__ :> ToExpression[x] + 1]
StringCases["item_10", "item_" ~~ x__ :> ToExpression[x <> "+1"]]

And step by step, first of all, :> not ->, the latter, Rule, is evaluated immediately:

x = 5;
StringReplace["item_10", "item_" ~~ x__ -> x]
StringReplace["item_10", "item_" ~~ x__ :> x]
StringExpression[5]
10

Then, you get a string "10", not a number so you have to perform appriopriate conversion first.

$\endgroup$
  • 2
    $\begingroup$ If working with integers using FromDigits is "safer" than ToExpression. $\endgroup$ – Mr.Wizard Mar 4 '15 at 19:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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