解析字符串输入的关键字和内容

标签 parsing rebol rebol3

我正在尝试解析一些字符串输入,但我很难找到解决方案。然而,这一定是一种众所周知的模式——只是我不经常遇到的模式。

背景:我有一个简短的字符串关键字列表(“HEAD”、“GET”、“POST”、“PUT”),每个关键字后面都跟有附加的字符串数据。可以有多个序列,以任何顺序(“KEYWORD blah blah blah KEYWORD blah blah blah”)。没有像 XML 那样的终止字符或结束关键字——要么是新出现的关键字子句,要么是输入的结尾。示例:

    str: {HEAD stuff here GET more stuff here POST other stuff here GET even more stuff here PUT still more stuff here POST random stuff}

我想要实现的输出:

    results: [
        "HEAD" ["stuff here"] 
        "GET"  ["more stuff here" "even more stuff here"] 
        "POST" ["other stuff here" "random stuff"] 
        "PUT"  ["still more stuff here"]
    ]

我对此的糟糕尝试是:

    results: ["head" [] "get" [] "post" [] "put" []]
    rule1: ["HEAD" (r: "head") | "GET" (r: "get") | "POST" (r: "post") | "PUT" (r: "put")]
    rule2: [to "HEAD" | to "GET" | to "POST" | to "PUT" | to end]

    parse/all str [
        some [
            start: rule1 rule2 ending: 
            (offs: offset? start ending 
            append select results r trim copy/part start offs
            ) :ending 
        | skip]
    ]

我知道规则 2 很糟糕——使用“to”运算符并不是考虑这种模式的正确方法;当我希望它找到任何关键字时,它会跳到该规则 block 中第一个可用关键字的下一个出现位置。

如有任何提示,我们将不胜感激。

最佳答案

这个怎么样...

;; parse rules
keyword: [{HEAD} | {GET} | {POST} | {PUT}]
content: [not keyword skip]

;; prep results block... ["HEAD" [] "GET" [] "POST" [] "PUT" []]
results: []
forskip keyword 2 [append results reduce [keyword/1 make block! 0]]

parse/case str [
    any [
        copy k keyword copy c some content (
            append results/:k trim c
        )
    ]
]

使用您的str,然后结果将得到您想要的......

["HEAD" ["stuff here"] "GET" ["more stuff here" "even more stuff here"] "POST" ["other stuff here" "random stuff"] "PUT" ["still more stuff here"]]

关于解析字符串输入的关键字和内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36000245/

相关文章:

parsing - Scala组合器解析器,>>是什么意思?

parsing - ANTLR 与预煮

java - 使用 GSON 解析 JSON 提要并获取数组而不是多参数

user-interface - 有没有办法在 Rebol 中将 gui 按钮和字段居中?

rebol - 如何从一系列函数中检索一个函数并调用它

php - 当字符串变量中有 URL 时,如何在 PHP 中使用 parse_url?

rebol - 从 Rebol 中的系列中删除重复的对象

rebol - 如何忽略解析时注释掉的行?

rebol - `context` 和 `object` 和有什么区别?

Rebol 3 - 如何使用 Saphirion 的 Rebol 的 view/new 的等效项进行调试