Lua gsub second instance

1.3k views Asked by At

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?

3

There are 3 answers

0
Paul Kulchenko On BEST ANSWER

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 %.

1
lhf On

Try string.gsub(mystring,"(.- .-) ", "%1/",1).

0
siffiejoe On

You can use a function as replacement value in string.gsub and count the matches yourself:

local mystring = "Thats a really nice house."
local cnt = 0
print( string.gsub( mystring, " ", function( m )
  cnt = cnt + 1
  if cnt == 2 then
    return "/"
  end
end ) )