# Get math from string . . .

## Recommended Posts

I have a list of text entries.

EX

\$sString = "Do you know what 2+2 is?

I would like to break that down and return 4

How do you convert text to numbers and then get math?

Edited by Hatcheda

##### Share on other sites

There are tons of ways to do that. Getting them from an arbitrary string will be hard though.

I'm using the Shunting Yard algorithm. http://en.wikipedia.org/wiki/Shunting_yard_algorithm

This will allow you to convert the text from infix to postfix notation, which is very easy to process.

##### Share on other sites

I'm sure not the best way, but works with that string:

```Dim \$sString = "Do you know what 2+2 is?"
\$x = Execute(StringRegExpReplace(\$sString, "[^0-9+*/\^()-]", ""))
MsgBox(1,"",\$x)```

Edit: Oops, the "-" has to be at the end of the string... and "^" needs the "\" esc character. fixed

Edited by Spiff59

##### Share on other sites

Execute doesn't seem to like a leading "-"

This seems to work better:

```Dim \$sString = "Do you know what -2 + (2 * 4) + 7  is?"
\$x = StringRegExpReplace(\$sString, "[^0-9+*/^()-]", "")
If Stringleft(\$x, 1) = "-" Then \$x = "0" & \$x
MsgBox(1,"",Execute(\$x))```

typo

Edited by Spiff59

##### Share on other sites

THanks :-) Looking the first post up now

for second: Works great but misses on more complex parts

Dim \$sString = "Do you know what 2+2*2 is?"

\$x = Execute(StringRegExpReplace(\$sString, "[^0-9+*/\^()-]", ""))

MsgBox(1,"",\$x)

Edit: just noticed you replied while I was -Checking new version now!

Edit: Works great!!! Thanks alot!!!

Edited by Hatcheda

##### Share on other sites

It works for everything I've tried so far: 2+2*4=10, (2+2)*4=16, 5+2^4=21, etc

I'm sure it would choke with operators other than + - * / ^ and parens.

Edit: Including "=" , "<" and ">" in the SRER works with execute evaluating the statement and returning a "True" or "False"

```Dim \$sString = "Do you know what -5+7* (6-4)^2 is?"
\$x = Execute("0+" & StringRegExpReplace(\$sString, "[^0-9+*/^()=<>-]", ""))
MsgBox(1, "", \$x)```

Another edit: I guess it wouldn't hurt to always tack a "0" on front and remove the test for "-". Using "0+" works with a leading "-" or a leading paren. So, changed code again. Final version lol

Edited by Spiff59

## Create an account

Register a new account

×

• Wiki

• Back

• Git