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

背景:我有一个字符串关键字(“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”运算符并不是考虑这种模式的正确方式;当我希望它找到任何关键字时,它会跳到该规则块中第一个可用关键字的下一次出现。

任何提示将不胜感激。

最佳答案

这个怎么样...

;; 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 然后 results 将拥有您想要的....
["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/

10-17 00:08