Lua如何从字符串的末尾去掉".html"文本

因此,我有一个Lua字符串,我想要删除所有出现在字符串末尾的".html"文本

local lol = ".com/url/path/stuff.html"

print(lol)

希望的输出:

.com/url/path/stuff

local lol2 = ".com/url/path/stuff.html.html"

print(lol2)

希望的输出:

.com/url/path/stuff
点赞
用户4403144
用户4403144

首先,您可以定义一个类似于以下代码的函数:

function removeHtmlExtensions(s)
    return s:gsub("%.html", "")
end

然后:

local lol = ".com/url/path/stuff.html"
local lol2 = ".com/url/path/stuff.html.html"

local path1 = removeHtmlExtensions(lol)
local path2 = removeHtmlExtensions(lol2)

print(path1) -- .com/url/path/stuff
print(path2) -- .com/url/path/stuff

gsub 方法中,还有一个返回值指示模式匹配的次数。例如,path1 返回值是 1path2 返回值是 2。(如果这个信息对您有用):

local path2, occurrences = removeHtmlExtensions(lol2)

print(occurrences) -- 2
2018-08-16 01:32:18
用户4984564
用户4984564

可以使用一个尾递归函数很容易地实现这个功能,代码如下:

local function foo(bar)
  if bar:find('%.html$') then return foo(bar:sub(1, -5) else return bar end
end

具体实现:

  • 如果 bar 以 '.html' 结尾,去掉最后5个字符并重新调用 foo 函数(以去除其它的出现)
  • 否则,返回 bar 本身

优点:

  • 尾递归,因此即使出现非常长的链也不会导致栈溢出
  • string.find 当锚点是字符串末尾时,搜索速度很快
  • string.gsub(须知这两个函数尽管名字相似,但是却有完全不同的功能)相比,string.sub 也要快的多。
2018-08-17 06:21:15