Lua中替换字符串中的最后一个逗号

我有这个字符串

Apples, Oranges, Grapes

如何将最后一个逗号替换为and

我还没有学习足够的模式,但我尝试了几种方法,比如

str:gsub(",$", "and", 1)

难道不应该使用魔法字符**$**从末尾-->开始读取字符串吗?

我的问题是因为我正在使用table.concat连接数组

原文链接 https://stackoverflow.com/questions/71268329

点赞
stackoverflow用户2858170
stackoverflow用户2858170
local str = "Apples, Oranges, Grapes"
print(str:gsub(",(%s+%w+)$", " and%1"))

str 里最后一个逗号之后的单词前加上 and

2022-02-25 15:58:06
stackoverflow用户1847592
stackoverflow用户1847592

你的表格:

local t = {"苹果", "橘子", "葡萄"}

方法 #1: 使用 "and" 连接最后一个项目:

local s = #t > 1
          and table.concat(t, ", ", 1, #t-1).." and "..t[#t]
          or  table.concat(t, ", ")
print(s)  --> 苹果, 橘子和葡萄

方法 #2: 替换最后一个逗号:

local s = table.concat(t, ", ")
s = s:gsub("(.*),", "%1 and")
print(s)  --> 苹果, 橘子和葡萄
2022-02-25 16:01:24