我正在尝试解码以下字符串:
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 inside brackets使用正则表达式?
我的尝试(仍然在每个管道上分裂):
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]"]
]
期待:
->
[
["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]"]
]
有谁知道这里需要的正则表达式?
是否可以匹配这个正则表达式?我似乎无法正确修改正则表达式以匹配不被括号括起来的下划线?
我在这里修改了答案Split string in Ruby, 忽略括号的内容?要得到:
self.body.scan(/\{(.*?)\}/).map {|m| m[0].split(/\|\s*(?=[^\[\]]*(?:\[|$))/)}
似乎可以解决问题。虽然我确定是否有任何不足之处。