Jump to content

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
Link to comment
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
Link to comment
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
Link to comment
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
Link to comment
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
Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...