问题描述
我通过Tasker(Android应用程序)将此HTTP POST请求发送到我的NodeMCU,如下所示:
I sent this HTTP POST request via Tasker (Android app) to my NodeMCU, which looks like this:
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>
我只想提取< action>之间的内容和< SetVolume>参数。我该怎么做?
I only want to extract what is between the "<action>" and "<SetVolume>" parameters. How can I do that?
推荐答案
此函数允许您从两个字符串分隔符之间提取文本:
This function allows you to extract text from between two string delimiters:
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
到字符串的结尾。
This is a modification of the above function that allows nil
for either of the parameters init
or term
. If init
is nil
, then text is extracted up to the term
delimiter. If term
is nil
, then text is extracted from after init
to the end of the string.
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>
这篇关于如何从lua发送给NodeMCU的http请求中获取post参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!