Question

I would like to take a string representing a file path, strip off the file name and save just the path.

For example, if I have:

"/folder1/folder2/file.name"

I would like to end up with "/folder1/folder2/" in my string.

I've been playing around with string.match() as documented here: http://lua-users.org/wiki/StringLibraryTutorial

I have the following code:

mystring = "/var/log/test.log"
print(string.match(mystring, "%/"))

When I run this script, I end up with just a '/' returned. I was expecting that it would return the positions of the two '/' in the string. I've also tried replacing the pattern "%/" with just "/" but that gives me the same results.

I'm sure I'm missing something very simple but I can't see what it is.

Was it helpful?

Solution

By the pattern %/ or /, you are telling string.match to look for a string / and that's what you got. Try with this:

local mystring = "/var/log/test.log"
print(string.match(mystring, ".+/"))

Here the pattern .+/ means to look for one or more whatever characters(.) followed by a /. + means it's greedy, i.e, match as long as possible.

OTHER TIPS

Try any this options:

local mystring = "/var/log/test.log"
print(mystring:gsub('([%w+]+%.%w+)$',''))

output: /var/log/

local mystring = "/var/log/test.log"
print(mystring:match('^(/.+/)'))

output: /var/log/

Or too a simple function

    function anystring(string)
       local string = string:match('^(/.+/)')
       if anystring then
          return string
       else
          return false
       end
    end

local mystring = anystring('/var/log/test.log')

print(mystring)

output: /var/log/

You can be as specific as possible when putting the pattern to avoid code errors

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top