Message Boards Message Boards

2 Replies
0 Total Likes
View groups...
Share this post:

ToExpression and strings like "5--1", "5 is not a variable with a value"?

I've got some code that does some string manipulation to assemble small equations, e.g. "(5+3)*8", and from these assembled strings I'd like to convert them to expressions for evaluation. This works in most circumstances, except when the string assembly produces something like "5--1", which should be read as "Five minus negative one". Instead, Mathematica's ToExpression function evaluates "--" as the Decrement function, which of course won't work since 5 is an integer, not a variable pointing to an integer that could be decremented.

Any thoughts on ways to change this behavior, apart from adding a space, e.g. "5- -1"?

POSTED BY: Christopher Fox
2 Replies

The main reason why it does what it does is because of the precedence of the operators:


I'm not sure if you can alter these because it will have huge effect on all the internal code as well...

POSTED BY: Sander Huisman
Posted 8 years ago

You can get the effect you want by using StringReplace to insert a space between the two minus signs as,

s = "5--1";
ToExpression[StringReplace[s, "--" -> "- -"]]
POSTED BY: Louis Godwin
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract