从URL获取参数,在查询字符串中获取子字符串并将其存储在表中

时间:2014-07-22 11:08:52

标签: string parsing url lua substring

我想获取URL中某些参数的值,我知道这个想法,但我不知道怎么做才能得到它们。

我有一个URL:

local url="fbconnect://success?to[0]=213322147507203&to[1]=223321147507202&request=524210977333164"

我想检测子串"到["并获取数字293321147507203,293321147507202并将它们存储在一个表中。

我知道进程检测到子字符串为[然后得到3个字符的子字符串(或6个不确定它是否从&#34开始计数到["然后]得到号码,总是15位数。

2 个答案:

答案 0 :(得分:3)

local url="fbconnect://success?to[0]=213322147507203&to[1]=223321147507202&request=524210977333164"
local some_table = {}
for i, v in url:gmatch'to%[(%d+)]=(%d+)' do
   some_table[tonumber(i)] = v  -- store value as string
end
print(some_table[0], some_table[1]) --> 213322147507203 223321147507202

答案 1 :(得分:2)

在这里,一个稍微更通用的解决方案,用于解析查询字符串,支持字符串和整数键,以及implicit_integer_keys[]

function url_decode (s)
    return s:gsub ('+', ' '):gsub ('%%(%x%x)', function (hex) return string.char (tonumber (hex, 16)) end)
end 

function query_string (url)
    local res = {}
    url = url:match '?(.*)$'
    for name, value in url:gmatch '([^&=]+)=([^&=]+)' do
        value = url_decode (value)
        local key = name:match '%[([^&=]*)%]$'
        if key then
            name, key = url_decode (name:match '^[^[]+'), url_decode (key)
            if type (res [name]) ~= 'table' then
                res [name] = {}
            end
            if key == '' then
                key = #res [name] + 1
            else
                key = tonumber (key) or key
            end
            res [name] [key] = value
        else
            name = url_decode (name)
            res [name] = value
        end
    end
    return res
end

对于网址fbconnect://success?to[0]=213322147507203&to[1]=223321147507202&request=524210977333164&complex+name=hello%20cruel+world&to[string+key]=123,它会返回:

{
  ["complex name"]="hello cruel world",
  request="524210977333164",
  to={ [0]="213322147507203", [1]="223321147507202", ["string key"]="123" } 
}