Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua trailing space removal

Tags:

string

lua

I'm using Lua in the NodeMCU environment. I saw the approach for whitespace trimming presented in this question.

The answer suggests this form:

str = string.gsub(str, "%s+", "")

I found it does not have any effect. Here is output from interactive commands (using LuaLoader).

> print("|",part1,"|")
|   172.16.0.19 |
> part1a = string.gsub(part1, "%s+", "")

> print("|",part1a,"|")
|   172.16.0.19 |
> 

If I examine the strings in hex, I see that there are some tabs. Apparently %s (the whitespace pattern) does not consider tab a whitespace. Is there a setting to cause %s to match tab (0x09)?

like image 597
tim11g Avatar asked Jul 18 '26 14:07

tim11g


2 Answers

The print function prints its arguments with tabs between them (after converting them to strings with tostring). To check this properly, use io.write (which does not add tabs between its arguments and only converts numbers to strings):

str = '   172.16.0.19 '
stripped = string.gsub(str, '%s+', '')
io.write('|', str, '|\n')
io.write('|', stripped, '|\n')

Note that this will remove all spaces and newlines, even if they are inside the string. To remove those on either end:

str = string.gsub(str, '^%s*(.-)%s*$', '%1')

or at the ends of lines and the end of the string:

str = string.gsub(str, '[ \t]+%f[\r\n%z]', '')
like image 156
cyclaminist Avatar answered Jul 20 '26 11:07

cyclaminist


Instead of print(something,somethingElse), do print(something..somethingElse). Concatenate the separate components - don’t just print a comma-separated list of the strings.

like image 37
brianolive Avatar answered Jul 20 '26 10:07

brianolive



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!