How to implement string.rfind in Lua

In Lua, only string.find , but sometimes string.rfind . For example, to parse the directory and file path, for example:

 fullpath = "c:/abc/def/test.lua" pos = string.rfind(fullpath,'/') dir = string.sub(fullpath,pos) 

How to write such a string.rfind ?

+8
string lua lua-patterns
source share
2 answers

You can use string.match :

 fullpath = "c:/abc/def/test.lua" dir = string.match(fullpath, ".*/") file = string.match(fullpath, ".*/(.*)") 

Here in the template,. .* Is greedy, so it will match as much as it can before it /

UPDATE

As @Egor Skriptunoff points out, this is better:

 dir, file = fullpath:match'(.*/)(.*)' 
+5
source share

The answers of Yu and Yegor work. Another possibility using find is to change the line:

 pos = #s - s:reverse():find("/") + 1 
+2
source share

All Articles