如何使用PARSE解析字符串中的货币值

时间:2014-07-31 12:00:08

标签: parsing rebol

我正在尝试使用字符串中的Rebol 2/3解析货币值,货币值的格式为:

10,50€或10,50€

我在查看了所有PARSE文档后得出的这段代码,我发现它可以用Red实现,但不能用于Rebol 2或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)
    ]
]

在玩了很长一段时间之后,我得出的结论是TO / THRU由于某种原因不适用于数字(它似乎与字符一起使用),但我无法弄清楚如何解析这个没有TO / THRU,因为字符串有任意内容需要跳过。

结果:

(来自tryrebol)

红色:

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

1 个答案:

答案 0 :(得分:3)

使用TO和THRU并不适合模式匹配(至少目前在Rebol中)。

如果您只搜索货币,则可以创建符合货币或前进步骤的规则:

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
    ]
]

请注意,由于EURO与您正在寻找的货币序列完全匹配,因此您只需使用COPY将序列分配给单词即可。这应该在Rebol和Red中都有效(尽管你需要在Rebol 2中使用PARSE / ALL)。

相关问题