Search code examples
stringlualua-patterns

Extracting a string format using lua


I have a string

(A file location) = "C:\User\Projects\54a2135.tif"

There are several tiff files in the location and I will need to pick them and move them to a different folder.

My difficulty is in getting only the .tif file . I tried string.match, string.gsub, string.find but unable to achieve that. Is there any advice on how I extract just the .tif file (In this case 54a2135.tif) from that string?


Solution

  • To start with, \ is the escape character, so it should be escaped in double/single quoted strings. (The other option is to use the long string [[...]])

    Then you can use pattern matching:

    local path = "C:\\User\\Projects\\54a2135.tif"
    print(path:match("[^\\]*$"))
    

    The pattern [^\\]*$ matches any non-backslash characters at the end of the string.

    If you like to specify it's a .tif file, change the pattern to [^\\]*%.tif$