Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse currency values from a string using PARSE

Tags:

parsing

rebol

I'm trying to parse currency values with Rebol 2/3 from a string, the currency values are in the format:

10,50 € OR 10,50€

This code I came up with after going through all PARSE documentation I could find works in Red, but not in Rebol 2 or 3.

digit: charset [#"0" - #"9"]
digits: [some digit]

euro: [digits "," digits [any " "] "€"]

parse "hello 22 44,55€ 66,44 €  33 world" [
    some [
        to euro
        copy yank thru euro
        (print yank)
    ]
]

After playing around with this for quite a while I came to the conclusion that TO/THRU doesn't work with numbers for some reason (it does seem to work fine with characters), but I can't figure out how to parse this without TO/THRU since the string has arbitrary contents that need to be skipped over.

Results:

(from tryrebol)

Red:

44,55€
66,44 €

Rebol 3:

*** ERROR
** Script error: PARSE - invalid rule or usage of rule: [some digit]
** Where: parse try do either either either -apply-
** Near: parse "hello 22 44,55€ 66,44 €  33 world" [
    some [
     ...

Rebol 2:

*** ERROR
code: 305
type: script
id: invalid-arg
arg1: [digits "," digits [any " "] "€"]
arg2: none
arg3: none
near: [parse "hello 22 44,55€ 66,44 €  33 world" [
        some [
            to euro 
            copy yank thru euro 
            (print yank)
        ]
    ]]
where: none
like image 342
SeriousNonsense Avatar asked Oct 20 '22 04:10

SeriousNonsense


1 Answers

Using TO and THRU isn't ideal for pattern matching (at least in Rebol at this time).

If you're only searching for currency, you can create a rule that either matches currency or steps forward:

digit: charset [#"0" - #"9"]
digits: [some digit]

euro: [digits opt ["," digits] any " " "€"]

parse "hello 22 44,55€ 66,44 €  33 world" [
    ; can use ANY as both rules will advance if matched
    any [
        copy yank euro (probe yank)
        | skip ; no euro here, move forward one
    ]
]

Note that as EURO is a complete match for the currency sequences you're looking for, you can just use COPY to assign the sequence to a word. This should work in both Rebol and Red (though you'll need to use PARSE/ALL in Rebol 2).

like image 200
rgchris Avatar answered Oct 29 '22 05:10

rgchris