Extract the last part of a string in Lua

I need to extract the last part of a line like this,

http://development.dest/show/images-345/name/289/

      

I need this part 289

, I tried to use string.match

with the following template.

string.match(url, "(%d+)(\/)$")

      

And I am getting this error in the error log,

2017/05/22 20:53:04 [error] 31264#0: *5 failed to load external Lua file

      

I think the last part of the pattern is wrong, but I don't know how to fix it ( (\/)

).

+3


source to share


2 answers


Error message from Lua

invalid escape sequence near '"(%d+)(\/'

      

which says it is \/

not a valid escape sequence in Lua strings.

The simpler figure below works just fine:



print(string.match(url, "(%d+)/$"))

      

If the last slash is optional, use

print(string.match(url, "(%d+)/?$"))

      

+4


source


Use LuaSocket to handle urls. This way you can also easily analyze the protocol, request, etc., without going into adhesive hell.



local url = assert(require"socket.url")

local parsed_url = url.parse"http://development.dest/show/images-345/name/289/"
local path       = url.parse_path(parsed_url.path)

print(path[#path])

      

+4


source







All Articles