Search code examples
lua

Replacing sub pathnames in lua doesn't work as expected


I have the following code:

local a = "/Users/diego/Desktop/nvim-file-location/lua/nvim-file-location/init.lua"
local b = "/Users/diego/Desktop/nvim-file-location"

local r = a:gsub(b, "")

print("path:", a)
print("cwd:", b)
print("replaced:", r)

I expect the following output for the replaced one:

replaced: /lua/nvim-file-location/init.lua

But I get:

path: /Users/diego/Desktop/nvim-file-location/lua/nvim-file-location/init.lua
cwd: /Users/diego/Desktop/nvim-file-location
replaced: /Users/diego/Desktop/nvim-file-location/lua/nvim-file-location/init.lua

Why it's not working?

I've tried also this:

local a = "/user/diego/foo"
local b = "/diego/foo"

local r = a:gsub(b, "/diego")

print(r)

And the output is as expected!!

/user/diego

Why is this happening? How can I solve this problem?


Solution

  • The second parameter to string.gsub (in this case b) is always interpreted as a Pattern. And in a pattern, the character - has a special meaning: It is the non-greedy version of *.

    So the portion m-f of the pattern can match f, mf mmf, etc., but there is nothing to match a - verbatim, so it cannot match a string m-f.

    To be able to use your pattern verbatim, you need to escape all special characters, as described in the Reference Manual linked above:

    local b = "/Users/diego/Desktop/nvim%-file%-location"