我通过Tasker(Android应用)将此HTTP POST请求发送到我的NodeMCU,如下所示:
POST / HTTP/1.1
Content-Type: application/x-www-form-urlencoded
User-Agent: Tasker/4.9u4m (Android/6.0.1)
Connection: close
Content-Length: 10
Host: 192.168.0.22
Accept-Encoding: gzip
<action>Play</action><SetVolume>5</SetVolume>
我只想提取&#34;&lt; action&gt;&#34;之间的内容。和&#34;&lt; SetVolume&gt;&#34;参数。我怎么能这样做?
答案 0 :(得分:1)
此功能允许您从两个字符串分隔符之间提取文本:
function get_text (str, init, term)
local _, start = string.find(str, init)
local stop = string.find(str, term)
local result = nil
if _ and stop then
result = string.sub(str, start + 1, stop - 1)
end
return result
end
示例互动:
> msg = "<action>Play</action><SetVolume>5</SetVolume>"
> get_text(msg, "<action>", "<SetVolume>")
Play</action>
> get_text(msg, "<action>", "</SetVolume>")
Play</action><SetVolume>5
这是对上述功能的修改,允许nil
参数init
或term
。如果init
为nil
,则文本将被提取到term
分隔符。如果term
为nil
,则会将文本从init
之后提取到字符串的末尾。
function get_text (str, init, term)
local _, start
local stop = (term and string.find(str, term)) or 0
local result = nil
if init then
_, start = string.find(str, init)
else
_, start = 1, 0
end
if _ and stop then
result = string.sub(str, start + 1, stop - 1)
end
return result
end
示例互动:
> msg = "<action>Play</action><SetVolume>5</SetVolume>"
> get_text(msg)
<action>Play</action><SetVolume>5</SetVolume>
> get_text(msg, nil, '<SetVolume>')
<action>Play</action>
> get_text(msg, '</action>')
<SetVolume>5</SetVolume>
> get_text(msg, '<action>', '<SetVolume>')
Play</action>
答案 1 :(得分:1)
为了完整起见,这是我想出的另一种解决方案:
string.gsub(request, "<(%a+)>([^<]+)</%a+>", function(key, val)
print(key .. ": " .. val)
end)
在您的问题中使用给定HTTP请求的工作示例可以在此处看到: