How to remove multi-line string in lua

Viewed 682

How do I make a multiline string into a single line string in lua?

I've tried this:

function removeMultilines(str)
    return str:gsub("\n")
end

But it doesn't work.

So basically, I would want to turn str1 into str2

local str1 = [[Hey,
how are you today?
Whats your name?]]

local str2 = "Hey, how are you today? Whats your name?"

Does anyone know how I can possibly approach that? Any help is welcome, just comment :D

2 Answers

Lua 5.3 Reference Manual: string.gsub (s, pattern, repl [, n])

Returns a copy of s in which all (or the first n, if given) occurrences of the pattern (see §6.4.1) have been replaced by a replacement string specified by repl, which can be a string, a table, or a function. gsub also returns, as its second value, the total number of matches that occurred. The name gsub comes from Global SUBstitution.

Covered at the bottom of Programming in Lua: 20.1 – Pattern-Matching Functions here is one of the examples:

s = string.gsub("Lua is cute", "cute", "great")
print(s)         --> Lua is great

Proper use of string.gsub requires the string, a pattern "\n" and the value replace the match with " ".

local str2 = str1:gsub("\r?\n", " ") --`\n` signifies the newline character
                                     --`\r?` add some handling for different line endings

Alternatively, you can use string.gmatch, though string.gsub is better suited for it replacement.

Proper use, for your case, could look like:

function removeMultilines(str)
    local lines = str:gmatch("([^\r\n]+)\r?\n?")
    local output = lines()

    for line in lines do
        output = output .. " " .. line
    end

    print(output)
    return output
end

Use str:gsub("\n"," ") in removeMultilines.

Use str:gsub("\n+"," ") to collapse blank lines.

Related