Search code examples
luagsublua-patterns

Lua gsub second instance


I'm using

local mystring = 'Thats a really nice house.'
string.gsub(mystring,"% ", "/",1)

to replace the first white space character with an slash.

But how to replace only the second occurrence of the white space?


Solution

  • You can replace the first instance with something else (assuming the replacement is not present in the string itself, which you can check), then replace it back:

    print(mystring:gsub("% ", "\1",1):gsub("% ", "/",1):gsub("\1","% ", 1))
    

    This prints: Thats a/really nice house.. Also, you don't need to escape spaces with %.