Lua how to remove “.html” text from end of string

倾然丶 夕夏残阳落幕 提交于 2021-02-05 06:37:25

问题


So I have a string in Lua and I want to remove all occurances ".html" text of the end of the string

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

print(lol)

Output i want :

.com/url/path/stuff


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

print(lol2)

Output i want :

.com/url/path/stuff

回答1:


First, you could define a function like this:

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

Then:

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

There is a second value returned from the gsub method that indicates how many times the pattern was matched. It returns, for example, 1 with path1 and 2 with path2. (Just in case that info is useful to you):

local path2, occurrences = removeHtmlExtensions(lol2)

print(occurrences) -- 2



回答2:


This can easily be done with a tail-recursive function like this:

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

in words:

  • If bar ends in '.html', remove the last 5 characters and feed that into foo again (to remove any more occurrences)
  • Otherwise, return bar as it is

Benefits:

  • Tail recursive, so it can't overflow the stack even for very long chains '.html'
  • string.find is pretty fast when you anchor the search to the end of the string with $
  • string.sub is also rather fast compared to, for example, string.gsub (note that those two do completely different things, despite the similar name).


来源:https://stackoverflow.com/questions/51868289/lua-how-to-remove-html-text-from-end-of-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!