如何删除 lua 中的多行字符串

How to remove multi-line string in lua

如何在 lua 中将多行字符串变成单行字符串?

我试过这个:

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

但是没用。

所以基本上,我想把 str1 变成 str2

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

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

有谁知道我该怎么做?欢迎任何帮助,请发表评论:D

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.

覆盖在 Programming in Lua: 20.1 – Pattern-Matching Functions 的底部,这里是示例之一:

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

正确使用 string.gsub 需要字符串、模式 "\n" 和值将匹配项替换为 " "

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

或者,您可以使用 string.gmatch,但 string.gsub 更适合替换它。

对于您的情况,正确使用可能如下所示:

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

removeMultilines中使用str:gsub("\n"," ")

使用str:gsub("\n+"," ")折叠空行。