Search code examples
stringlualua-patterns

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?


Solution

  • 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