Replace last comma on string Lua

Viewed 134

I have this string

Apples, Oranges, Grapes

How can i replace last comma for and?

Havent learn enough of patterns but i've tried several ways such as

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

Isnt supposed that magic character $ reads string from end --> begin?

My problem becomes because im concatenating an array using table.concat

2 Answers

Your table:

local t = {"Apples", "Oranges", "Grapes"}

Method #1: Concatenate the last item using "and":

local s = #t > 1 
          and table.concat(t, ", ", 1, #t-1).." and "..t[#t] 
          or  table.concat(t, ", ")
print(s)  --> Apples, Oranges and Grapes

Method #2: Replace the last comma:

local s = table.concat(t, ", ")
s = s:gsub("(.*),", "%1 and")
print(s)  --> Apples, Oranges and Grapes
local str = "Apples, Oranges, Grapes"
print(str:gsub(",(%s+%w+)$", " and%1"))
Related