我如何在Rebol中解析这个?

时间:2011-09-15 22:57:44

标签: parsing rebol

我将如何解析此字符串

"a:foo[and it's cousin bar[are here]]"

进入这个

"a:" "foo[" "and" "it's" "cousin" "bar[" "are" "here" "]" "]"

本质上我想要完成三件事,提取一个赋值“a:”,提取部分“foo [”(包括嵌套部分)和结束部分“]”。我可以均匀地分隔它们,只做一个简单的解析,但我不想这样做。

希望它有意义。任何帮助将不胜感激!

谢谢!

2 个答案:

答案 0 :(得分:3)

定义您的语言元素,然后在匹配时收集它们:

parse-my-language: use [word assignment section section-end space][

    word: use [letters][
        letters: charset [#"a" - #"z" ".'"]
        [some letters]
    ]
    assignment: [word ":"]
    section: [word "["]
    section-end: "]"

    space: charset " "

    func [statement /local out element][
        out: copy []
        if parse/all statement [
            any [
                copy element [
                    assignment | section | section-end | word
                ] (append out element)
                | some space
            ]
        ][out]
    ]
]

probe parse-my-language "a:foo[and it's cousin bar[are here]]"

注意:我使用'use来隔离仅用于此目的的单词。

答案 1 :(得分:2)

该示例的更多上下文可能会有所帮助,因为您可以在rebol中尝试很多选项。

一种简单的方法是“修复”你的字符串,使其更像普通的rebol数据。

source-string: "a:foo[and it's cousin bar[are here]]"
replace/all source-string "[" " [ "
replace/all source-string "]" " ] "
replace/all source-string ":" ": "
output: load source-string

很少在rebol中以这种方式使用字符串。块通常更灵活,更易于解析。

相关问题