如何在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参考手册:string.gsub(s,模式,repl [,n])
返回s的副本,其中模式的所有(或前n个,如果给定的话)出现(请参见第6.4.1节)已由repl指定的替换字符串替换,该替换字符串可以是字符串,表或a。功能。gsub还返回发生的匹配总数作为第二个值。gsub的名称来自Global SUBstitution。
在Lua编程的底部:20.1 –模式匹配功能此处是示例之一:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句