如何截断文本但向后?

How to truncate text but backwards?

我想实现这样的目标:

我给函数一个应该截断的字符串和最大字符数。

local function TruncateBackwards(str, maxChars)
  --Code
end

print(TruncateBackwards("this text should be truncated", 15)) -- ld be truncated

您可以为此使用 string.sub

local function TruncateBackwards(str, maxChars) return str:sub(-maxChars) end
print(TruncateBackwards("this text should be truncated", 15)) -- ld be truncated

这也使你自己的功能,TruncateBackwards,相当过时:

print(("this text should be truncated"):sub(-15)) -- ld be truncated

不需要索引数学,因为 Lua 索引是 one-indexed 并且 string.sub 支持相对于字符串末尾的负索引。

使用 gsub(),您可以使用以下模式执行此操作:'..%s%w+%s%w+$'
...或在 $ 之前加上 15 个点:'...............$'
...或者在 $ 之前重复 15 次点:('.'):rep(15) .. '$'

local txt, count = ("this text should be truncated"):gsub('..%s%w+%s%w+$', '')
print(txt)
-- That replaces the capture 'ld be truncated' with nothing
-- Output: this text shou
-- With match() and same pattern you can do the opposite
print(("this text should be truncated"):match('..%s%w+%s%w+$'))
-- Output: ld be truncated

参见:https://www.lua.org/manual/5.1/manual.html#5.4.1