Example:
I have a string: "Noobs RULE" and I want to remove " RULE" from it, so it turns into "Noobs".
How can I do that in Lua?
Example:
I have a string: "Noobs RULE" and I want to remove " RULE" from it, so it turns into "Noobs".
How can I do that in Lua?
You can use gsub to replace all substrings with something else. In this case it could be
str = str:gsub(" RULE", "");
Alternatively, if you just knew you wanted the first 5 characters ("Noobs"), you could just use sub:
str = str:sub(1, 5);
You could also take advantage of Lua's pattern matching and remove the spaces intelligently, though this makes more assumptions than you have stated:
str = " " .. str .. " ";
-- Pad with spaces
str = str:gsub("%s+RULE%s+", " ")
:gsub("%s+RULE%s*", " ")
:gsub("%s*RULE%s+", " ");
-- Replace [a]RULE[b] with a single space,
-- where [a] and [b] together are only space characters and
-- at least one space character.
str = str:gsub("^%s*(.-)%s*$", "%1");
-- Trim any extra space at the beginning or end of
-- the string (since we added some initially to make
-- the middle step work with first / last words)
This discussion is preserved as it was. New answers, comments, and votes are closed.
2 comments
Thanks a lot, I love ya.
I just fixed a typo in the last example, so if you were using that, check it!