我想下面的字符串解碼:Ruby的正則表達式前瞻在管道內來分割
body = '{type:paragaph|class:red|content:[class:intro|body:This is the introduction paragraph.][body:This is the second paragraph.]}'
body << '{type:image|class:grid|content:[id:1|title:image1][id:2|title:image2][id:3|title:image3]}'
我需要串在管道拆分而不是其中一個管被包含同方括號,要做到這一點,我想我需要執行一個超前如下所述:How to split string by ',' unless ',' is within brackets using Regex?
我嘗試(仍然分裂在每個管):
x = self.body.scan(/\{(.*?)\}/).map {|m| m[0].split(/ *\|(?!\]) */)}
->
[
["type:paragaph", "class:red", "content:[class:intro", "body:This is the introduction paragraph.][body:This is the second paragraph.]"]
["type:image", "class:grid", "content:[id:1", "title:image1][id:2", "title:image2][id:3", "title:image3]"]
]
Expectin G:
->
[
["type:paragaph", "class:red", "content:[class:intro|body:This is the introduction paragraph.][body:This is the second paragraph.]"]
["type:image", "class:grid", "content:[id:1|title:image1][id:2|title:image2][id:3|title:image3]"]
]
有誰知道這裏所需要的正則表達式?
是否有可能匹配這個正則表達式?我似乎無法正確地修改它Regular Expression to match underscores not surrounded by brackets?
我修改的答案在這裏Split string in Ruby, ignoring contents of parentheses?獲得:
self.body.scan(/\{(.*?)\}/).map {|m| m[0].split(/\|\s*(?=[^\[\]]*(?:\[|$))/)}
似乎這樣的伎倆。雖然我確定是否有任何不足之處。
您嘗試按管道拆分,但不包含一個,只能向前看一個字符,所以沒有看到管道。如果你把它放在更前面,你還需要聲明沒有開放支架。您還需要斷言沒有以前的開頭括號。在這個階段,值得考慮以不同的方式收集解析結構。 。 。 –
括號是否出現在封裝輸入字符串位的上下文中?也就是'this | [是一個字符串] |使用孤兒]的值嗎? –
不,它們只用於上述情況。 –