Jump to content

Parsing with StringRegExp


Recommended Posts

I've spent a few hours on this one and I can't get it exactly right (just almost right...)

$string = "+ST,000024.4 g"

$asResult = StringRegExp($string, "[-+]?\d*\.\d+|\d+",2)
If @error == 0 Then
    MsgBox(0, "Result", $asResult[0])
EndIf

The result is 000024.4 which is OK - I'd like the code to be 24.4 however.

Tricky part is that it the string can look like +ST,010232.2 g, or even +UT,000000.4 g (looking for 10232.2 and .4 respectively out of those 2 eg's)

o:)

Edited by methodman
Link to comment
Share on other sites

This is the way I would do it:

$string = "+ST,000024.4 g"
;~ $string = "+UT,010232.2 g"


Global $asResult = StringSplit($string, ",", 3)
MsgBox(0, "result", Number($asResult[1]))

Programming today is a race between software engineers striving to
build bigger and better idiot-proof programs, and the Universe
trying to produce bigger and better idiots.
So far, the Universe is winning.

Link to comment
Share on other sites

I believe we all agree the Number() function is the way to remove leading zeros and any trailing non-digit characters.

$string = "+ST,001024.4 g" ; "+UT,000000.4 g" ;

MsgBox(0, "Result RegExp", Number(StringRegExpReplace($string, "^.*,|\s.*$", '')), 3) ; Returns 1024.4

;or

MsgBox(0, "Result StringSplit", Number(StringSplit($string, ",", 3)[1])) ; Returns 1024.4
@methodman

If $string = "-ST,001024.4 g", hopefully you do not want -1024.4 returned - yes/no?

Link to comment
Share on other sites

Tricky part is that it the string can look like +ST,010232.2 g, or even +UT,000000.4 g (looking for 10232.2 and .4 respectively out of those 2 eg's)

 

For the .4 value, Number() will add a 0 at the beginning, so maybe just this :

$string = "+UT,000000.4 g"
; $string = "+ST,010232.2 g"

$asResult = StringRegExp($string, "0*([\d.]+)", 1)
MsgBox(0, "Result", $asResult[0])
Link to comment
Share on other sites

I was actually after 0.4 - figured it might be difficult to achieve so would have been OK with .4

Thanks for your efforts nonetheless!

 

For the .4 value, Number() will add a 0 at the beginning, so maybe just this :

$string = "+UT,000000.4 g"
; $string = "+ST,010232.2 g"

$asResult = StringRegExp($string, "0*([\d.]+)", 1)
MsgBox(0, "Result", $asResult[0])
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...