Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement string.rfind in Lua

In Lua there's only string.find, but sometime string.rfind is needed. For example, to parse directory and file path like:

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

How to write such string.rfind?

like image 925
mos Avatar asked Jun 30 '13 03:06

mos


People also ask

How do you use %s in Lua?

The % is also used to designate a character class in the pattern syntax used with some string functions. Show activity on this post. Lua uses %s in patterns (Lua's version of regular expressions) to mean "whitespace". %s+ means "one or more whitespace characters".

How do I match a string in Lua?

> = string. match("foo 123 bar", '%d%d%d') -- %d matches a digit 123 > = string. match("text with an Uppercase letter", '%u') -- %u matches an uppercase letter U. Making the letter after the % uppercase inverts the class, so %D will match all non-digit characters.

Can you index strings in Lua?

When indexing a string in Lua, the first character is at position 1, not at position 0 as in C. Indices are allowed to be negative and are interpreted as indexing backwards from the end of the string. Thus, the last character is at position -1, and so on.

What does string Sub Do in Lua?

Another important function of the Lua's string library is the string. sub() function. The string. sub() function is used to extract a piece of the string.


2 Answers

You can use string.match:

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

Here in the pattern, .* is greedy, so that it will match as much as it can before it matches /

UPDATE:

As @Egor Skriptunoff points out, this is better:

dir, file = fullpath:match'(.*/)(.*)'
like image 165
Yu Hao Avatar answered Oct 26 '22 17:10

Yu Hao


Yu & Egor's answer works. Another possibility using find would be to reverse the string:

pos = #s - s:reverse():find("/") + 1
like image 4
catwell Avatar answered Oct 26 '22 17:10

catwell