Retaker
Retaker

Reputation: 17

what does "(.+)"}], in lua pattern matching mean

i got this code that take webhook message but i dont understand the pattern matching behind it

function getContent(link)
    cmd = io.popen('powershell -command "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; Write-Host (Invoke-WebRequest -Uri "'..link..'").Content"')
    return cmd:read("*all"):match('"description": "(.+)"}],')
end

function blabla(a)
    link= webhookLink.."/messages/"..messageId
    text = [[
        $webHookUrl = "]]..link..[["
        $embedObject = @{
            description = "]]..getContent(link):gsub("\\([nt])", {n="\n", t="\t"})..[[`n]]..a..[["
        }
        $embedArray = @($embedObject)
        $payload = @{
            embeds = $embedArray
        }
        [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
        Invoke-RestMethod -Uri $webHookUrl -Body ($payload | ConvertTo-Json -Depth 4) -Method Patch -ContentType 'application/json'
    ]]
    file = io.popen("powershell -command -", "w")
    file:write(text)
    file:close()
end

My question is what does "(.+)"}] mean in the getContent function and ]]..getContent(link):gsub("\\([nt])", {n="\n", t="\t"})..[[n]]..a..[[ in blabla function ?

Upvotes: -2

Views: 88

Answers (3)

Luatic
Luatic

Reputation: 11201

Let's break up the pattern: "description": "(.+)"}],

  • "description": " - literal string that needs to match
  • (.+) - one or more of any character, greedy (+), captured
  • "}], - another literal string

That is, this pattern will match the first substring that starts with "description": ", followed by one or more characters which are captured, followed by "}],.

All in all, this pattern is a very unreliable implementation of extracting a certain string from what's probably JSON; you should use a proper JSON parser instead. This pattern will fail in all of the following cases:

  • Empty String: [[{"description": ""}],null] (might be intended)
  • Another String later on: [{"foo": [{"description": "bar"}], "baz": "world"}], null], which would match as bar"}], "baz": "world due to + doing greedy matching.

Upvotes: 2

Amrinder
Amrinder

Reputation: 11

https://gitspartv.github.io/lua-patterns/ This can help you greatly with pattern matching,

though, (.+) means capture any digit, with multiple repetations.

example: "ABC(.+)" would return everything after "ABC"

return cmd:read("*all"):match('"description": "(.+)"}],') Looks like this gets everything inside description: "THIS_IS_RETURNED"],

Upvotes: 1

Ivo
Ivo

Reputation: 23357

. means any character, and + means one or more. I suggest you to read up on the basics of patterns. For example: http://lua-users.org/wiki/PatternsTutorial

Upvotes: -1

Related Questions