Changing every instance in a string

Post Reply
User avatar
Akaya
Posts: 414
Joined: Thu Apr 19, 2012 1:36 am

Changing every instance in a string

Post by Akaya »

I have the following string:
Bob sits. A moment later, Bob stands. After that, Bob leaves.

I want to change every instance of Bob (no matter how many Bob's appear in the string) to the word Tom.
So...
Tom sits. A moment later, Tom stands. After that, Tom leaves.

This is what I'm currently using though it will only capture a single instance of the word:
Code: [show] | [select all] lua
selectString("Bob",1)
replace("Tom")

Jor'Mox
Posts: 1142
Joined: Wed Apr 03, 2013 2:19 am

Re: Changing every instance in a string

Post by Jor'Mox »

You could try this:
Code: [show] | [select all] lua
while selectString("Bob",1) > -1 do
   replace("Tom")
end
I didn't actually test that, but in theory it should select every instance of Bob, in turn, and replace it with Tom. When there are none left in the line, selectString will return -1, and the loop will end.

User avatar
Akaya
Posts: 414
Joined: Thu Apr 19, 2012 1:36 am

Re: Changing every instance in a string

Post by Akaya »

just what I need. Thanks!

Ginga Giri Giri
Posts: 11
Joined: Mon Dec 17, 2012 2:58 am

Re: Changing every instance in a string

Post by Ginga Giri Giri »

Alternative method:

string.gsub(matches[1], "Bob", "Tom")

User avatar
Vadi
Posts: 5035
Joined: Sat Mar 14, 2009 3:13 pm

Re: Changing every instance in a string

Post by Vadi »

Not quite - that replaces it within matches[1], but not on Mudlets screen.

Post Reply