gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:18:36 26 4
gpt4 key购买 nike

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

背景:我有一个简短的字符串关键字列表(“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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com