Remove spaces from a string but not new lines in lua

Viewed 548

I used string.gsub(str, "%s+") to remove spaces from a string but not remove new lines, example:

str = "string with\nnew line"
string.gsub(str, "%s+")
print(str)

and I'm expecting the output to be like:

stringwith
newline

what pattern should I use to get that result.

2 Answers

It seems you want to match any whitespace matched with %s but exclude a newline char from the pattern.

You can use a reverse %S pattern (that matches any non-whitespace char) in a negated character set, [^...], and add a \n there:

local str = "string with\nnew line"
str = string.gsub(str, "[^%S\n]+", "")
print(str)

See an online Lua demo yielding

stringwith
newline

"%s" matches any whitespace character. if you want to match a space use " ". If you want to define a specific number of spaces either explicitly write them down " " or use string.rep(" ", 5)

Related