【问题标题】:How to parse currency values from a string using PARSE如何使用 PARSE 从字符串中解析货币值
【发布时间】:2014-07-31 12:00:08
【问题描述】:

我正在尝试使用 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

【问题讨论】:

    标签: parsing rebol


    【解决方案1】:

    使用 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)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-06
      • 2012-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多