Jump to content
Sign in to follow this  
John117

Get math from string . . .

Recommended Posts

John117

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 this post


Link to post
Share on other sites
Richard Robertson

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 this post


Link to post
Share on other sites
Spiff59

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 this post


Link to post
Share on other sites
Spiff59

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 this post


Link to post
Share on other sites
John117

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 this post


Link to post
Share on other sites
Spiff59

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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×