2

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?

3
  • Do you mean to replace any letter followed with 1 space and exactly 1 letter? What if you have a bc c b, what is the expected result ? Commented Apr 14, 2017 at 11:03
  • any letter, space, b should result in a z so that should give zc z Commented Apr 14, 2017 at 11:05
  • Ok, so it is much easier, you do not even need to check if a whole word is matched. Commented Apr 14, 2017 at 11:12

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.