3

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.

ahmed
  • 88
  • 1
  • 9
  • 2
    if you just want spaces then use `" "` – Nifim Apr 04 '21 at 14:21
  • in lua patterns `%s` represent whitespace characters, which newline is too, so `string.gsub(str, "[ ]+", "")` should do what you want – Kazz Apr 04 '21 at 14:52

2 Answers2

5

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
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    that's what I was looking for, removing more than one space and not remove a new line. – ahmed Apr 05 '21 at 15:59
2

"%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)

Piglet
  • 27,501
  • 3
  • 20
  • 43