2

I have some magnet links being submitted as string in Lua. These magnets normally are of the format:

magnet:?xt=<hashing>&xl=<size>&dn=<name>

but with differences in the clients the magnets can also be generated as:

magnet:?xl=<size>&xt=<hashing>&dn=<name>

From this type of string, I want to fetch the data after xl=(which is pure number) and after xt= which consists of %w and :(where %w is alphanumeric match).

Currently I am using two separate statements to fetch these values. Can this be achieved in a single statement/string.find()?

sInput = "magnet:?xt=urn:tree:tiger:ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABC&xl=1234567890123456789&dn=This+Is+The+Name+Of+File.EXT"
local _, _, sHash = sInput:find( "xt=([%w%:]+)" )
local _, _, iSize = sInput:find( "xl=(%d+)" )

1 Answer 1

2

I think you'd be better off collecting all values into a table:

local sInput="magnet:?xt=<hashing>&xl=<size>&dn=<name>"
local s=sInput:match("%?(.*)$").."&"
local t={}
for k,v in s:gmatch("(%w+)=(.-)&") do
        t[k]=v
end

If you want to restrict to the keys starting with x then use gmatch("(x%w+)=(.-)&"). If you know that xt and xl are never the last item in the list, you can simply do:

for k,v in sInput:gmatch("(x%w+)=(.-)&") do
Sign up to request clarification or add additional context in comments.

1 Comment

FYI: he is one of the authors of Lua :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.