How to remove all special characters, punctuation and whitespaces from a string in Lua

lua

In Lua (I can only find examples in other languages), how do I remove all punctuation, special characters and whitespace from a string? So, for example, s t!r@i%p^(p,e"d would become stripped?

Best Solution

In Lua patterns, the character class %p represents all punctuation characters, the character class %c represents all control characters, and the character class %s represents all whitespace characters. So you can represent all punctuation characters, all control characters, and all whitespace characters with the set [%p%c%s].

To remove these characters from a string, you can use string.gsub. For a string str, the code would be the following:

str = str:gsub('[%p%c%s]', '')

(Note that this is essentially the same as Egor's code snippet above.)

Related Question