我需要解析这样的字符串:a [metadata] [] [name] = dont | do | this& a [name] = Hello World& a [metadata] [] [value] = i | really |意思是
CGI :: parse给了我这个:
{“a [name]”=> [“Hello World”],“a [元数据] [] [名称]”=> [“dont | do | this”],“a [元数据] [ ] [value]“=> [”我|真的|意思是“]}
我想要像PHP对parse_str所做的一样,当给出相同的字符串时,这就是:
Array
(
[a] => Array
(
[metadata] => Array
(
[0] => Array
(
[name] => dont|do|this
)
[1] => Array
(
[value] => i|really|mean it
)
)
[name] => Hello World
))
任何帮助都会很棒。
谢谢!
答案 0 :(得分:0)
还没有真正得到任何回复,仍然没有找到一个等效的功能,所以,为了我的目的,这是有效的,基于我发现_Why已经发布在现在丢失的redhanded.hobix.com或者什么没有
hash1 = {}
hash2 = {}
array1 = []
array2 = []
resulthash = {}
count = 0
count2 = 0
keynum2 = 0
main = 'base'
h3main = 'base'
st.scan(/([\w]+)(\[|=)(.*?)(?=(&[\w]+\[|&[\w]+=|$))/) {
var = $1 << $2 << $3
case var
when /^([\w]+)\[(.*?)\]\[(\d+)\]\[(.*?)\]=(.*?)$/ then
count2 += 1
h3main = $2
keynum2 = $2 << count2.to_s
i = $3.to_i
array1[i] = {} if array1[i].class != Hash
array1[i].update({$4 => $5})
hash2.update(keynum2 => array1)
when /^([\w]+)\[(.*?)\]\[\]\[(.*?)\]=(.*?)$/ then
count2 += 1
h3main = $2
keynum2 = $2 << count2.to_s
i = count2
array2[i] = {} if array2[i].class != Hash
array2[i].update({$4 => $5})
hash2.update(keynum2 => array2)
when /^([\w]+)\[(.*?)\]=(.*?)$/ then
main = $1
count += 1
keynum = $1 << count.to_s
hash1.update(keynum => {$2 => $3})
when /^(a)=(.*?)$/ then
resulthash.update($1 => $2)
end
}
hashx = {}
hash1.each_pair {|k,v| hashx.update(main => v) }
resulthash[main] = hashx
if not hash2.empty? then
if not resulthash[h3main].class == Hash then
resulthash[main][h3main] = {}
end
hash2.each_pair{ |k,v|
if v.class == Array then
resulthash[main][h3main] = v
else
resulthash[main][h3main].update(v)
end
}
end
以上有点工作,请注意,我知道如何分组[]项目的真实方式,因此它们作为单个项目在数组中。最好设置索引,如[somegroup] [0] [value]等。
这是复制粘贴和概括,因此需要注意。