Say I have a bunch of files that all follow the same pattern:
/tmp/project1/server_config.json
/tmp/project1/client_config.json
/tmp/project1/monitor_config.json
what I need is to extract the names:
server
client
monitor
If all I got is the full paths as a strings, is there a Lua method to extract the part that lies between /tmp/projectXX/ and _config.json ?
You need to be careful with the pattern. Assuming you want to match exactly the test strings you have given, where the filename may vary in the prefix, but the suffix needs to be _config.json, and the name of the project folder may vary in the suffix, use the pattern ^/tmp/project[^/]+/([^/]+)_config.json for string.match:
print(("/tmp/project[^/]+/server_config.json"):match"^/tmp/project1/([^/]+)_config.json") -- server
Note also the nuances in the patterns by the other answerers:
/tmp/project%d+/(.-)_config.json misses anchors (^ and $). (Assuming this is unintended) this is a frequent mistake in Lua patterns. This will match anything that has something matching /tmp/project%d+/(.-)_config.json anywhere in it; it will also accept the *_config.json file being included in a subdirectory of the project. The following will match, for example: /foo/bar/tmp/project42/subfolder/server_config.json.blah.blub, and the match would be subfolder/server..*/(.+)_config.json effectively matches just the filename, and removes a suffix of _config.json. Note that this also isn't anchored. A ^ anchor isn't needed here, as .* being greedy already suffices to start at the start of the string, but this pattern will allow arbitrary suffixes after _config.json. It will also allow arbitrary parent folders as it matches just the filename. /blah/blub/server_config.json.blah.blub would match as just server./tmp/project[1-9]*/(.+)_config.json is similar to the first pattern in that it isn't anchored. It will pretty much have the same issues; it allows [1-9]* rather than %d+ as the project folder suffix though.You can use a string.match on your names and specify the correct regex like so:
local file_path = "/tmp/project1/client_config.json"
local filename_no_config = string.match(file_path, "/tmp/project[1-9]*/(.+)_config.json")
print(filename_no_config)
In this case print will write client and will work for project followed by whatever number (even bigger than 2 digits)
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