3

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?

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
frgtv10
  • 5,300
  • 4
  • 30
  • 46

3 Answers3

5

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 ) )
siffiejoe
  • 4,141
  • 1
  • 16
  • 16
5

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

lhf
  • 70,581
  • 9
  • 108
  • 149
3

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

Paul Kulchenko
  • 25,884
  • 3
  • 38
  • 56