darkchampionz
darkchampionz

Reputation: 1224

LUA replace instances of string

I have a string x = "a b c d e f g e b" And I am trying to replace every instance of x b where x is any character with the letter z let's say, so the above should be x = z c d e f g z. I have looked up in examples but they all mention specific characters replacement with string.gsub, how can the above be done?

Upvotes: 2

Views: 5116

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You may use

string.gsub(x, "%a b", "z")

where %a matches any letter.

See more on Lua pattern here.

Lua demo:

x = [[a b c d e f g e b]]
res, _ = string.gsub(x, "%a b", "z")
print(res)
-- z c d e f g z

Upvotes: 3

Related Questions