Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract last part of a string in Lua

Tags:

lua

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

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

I only need this part 289, I tried using string.match with the next pattern.

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

And I get this error in 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 ((\/)).

like image 354
Ismael Moral Avatar asked Feb 04 '23 10:02

Ismael Moral


2 Answers

The error message from Lua is

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

which says that \/ is not a valid escape sequence in Lua strings.

The simpler pattern below works just fine:

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

If the final slash is optional, use

print(string.match(url, "(%d+)/?$"))
like image 80
lhf Avatar answered Feb 16 '23 04:02

lhf


Use LuaSocket to handle URLs. This way you can also easily parse out the protocol, the query, etc without having to go through regex 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])
like image 25
Henri Menke Avatar answered Feb 16 '23 05:02

Henri Menke