2016-03-14 54 views
4

我想解析一些字符串輸入,但我很努力地看到解決方案。但是,這必須是一個衆所周知的模式 - 這只是我不經常遇到的模式。解析字符串輸入的關鍵字後跟內容

背景:我有字符串的關鍵字的短列表(「頭」,「GET」,「POST」,「PUT」)其中的每一個隨後附加字符串數據。可以有任意順序的多個順序(「KEYWORD等等等等等等等)」。 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是clunker-- 「to」運算符的使用不是考慮這種模式的正確方法;當我想它找到任何關鍵字它跳過到規則塊中的第一個可用關鍵字的下一個occurrance。

任何提示將不勝感激。

回答

2

這個怎麼樣...

;; 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"]] 
+0

感謝 - 這去draegtun和sqlab - 我意識到,一個簡單的作弊是對我來說,我自己的終結者添加到輸入,但我很感激看到更多的語法分析適當的方法。 – Edoc

2

也許不那麼優雅,但即使Rebol2

工作
results: ["HEAD" [] "GET" [] "POST" [] "PUT" []] 
keyword: [{HEAD} | {GET} | {POST} | {PUT}] 
parse/case str [ 
    any [ 
     [copy k keyword c1: ] | [skip c2:] 
     [[keyword | end] (
      append results/:k trim copy/part c1 c2 
     ) :c2 | 
     ] 
    ] 
] 
1

這是另一種變體。

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" [] "GET" [] "POST" [] "PUT" []] 
possible-verbs: [ "HEAD" | "GET" | "POST" | "PUT" | end ] 
parse/all str [ 
    some [ 
     to possible-verbs 
     verb-start: (verb: first split verb-start " ") 
     possible-verbs 
     copy text to possible-verbs 
     (if not none? verb [ append results/:verb trim text ]) 
    ] 
] 
probe results 

再一次,在優雅和方法上並不完美。