Search code examples
stringluasubstringlua-patternsnodemcu

Find substring between specific characters


I am unfamiliar with Lua language and a I would like your help. I am trying to receive some values through POST and the values is something like that:

pwd = password
ssid = ssid_name

swstat={string.find(payload,"pwd=")}
swstat1={string.find(payload,"ssid=")}
if swstat[2]~=nil then
    pass=string.sub(payload,swstat[2]+1,#payload)
    ssid=string.sub(payload,swstat1[2]+1,#payload)
    print("Password: "..pass)
    print("SSID: "..ssid)
end

The actual result of the above code is ( am sending through a web browser the ssid=htc and password=fr):

Password: fr
SSID: htc&pwd=fr

I would like to have in a string the password only and in another string the ssid. So my idea is to search into string with the following logic: ssid = find in string the sub string which is between "ssid=" and ("&" or end of string) pwd = find in string the sub string which is between "pwd=" and ("&" or end of string)


Solution

  • Since payload is a valid query string format, you can store related information inside a table:

    local tData = {}
    for sParam, sValue in payload:gmatch "([^=&]+)=([^=&]+)" do
        tData[sParam:lower()] = sValue
    end
    

    Now, you'll have the information inside the tData table:

    tData.pwd     -- will have fr
    tData.ssid    -- will have htc