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
?
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".
> = 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.
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.
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.
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'(.*/)(.*)'
Yu & Egor's answer works. Another possibility using find would be to reverse the string:
pos = #s - s:reverse():find("/") + 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With