简体   繁体   中英

How do I remove all special characters, punctuation and whitespaces from a string in 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, st!r@i%p^(p,e"d would become stripped ?

If you remove all special chars, whitespace, … all that's left is letters and numbers, right? So if str is your string,

str:gsub( "%W", "" )

will be the cleaned string.

%w matches all word characters, upper-case it %W to match all non-word characters. If that's not exactly what you want to match, you can build your own character class -- eg if you wanted to include _ as an acceptable character, you could use [^%w_] .

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 .)

这对我有用

m=your_string:gsub('%W','')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM