-- gmatch даёт части, подходящие под шаблон
local function split(text, pattern)
local parts = {}
for part in text:gmatch(pattern) do
parts[#parts + 1] = part
end
return parts
end
local str_data = "1981|Kim Victoria|engineer"
-- [^|]+ - последовательность любых символов, кроме |
local lst_data = split(str_data, "[^|]+")
-- lst_data = 1981, Kim Victoria, engineer
-- Распаковка: по одному имени на часть
local year_text, name, position =
table.unpack(lst_data)
-- name = Kim Victoria
-- position = engineer
local year = tonumber(year_text)
-- year = 1981
-- %S+ - последовательность непробельных символов: любая серия пробелов -
-- один разделитель
local words = split("red green blue", "%S+")
-- words = red, green, blue
-- Пустые поля теряются
local csv = "red,,green"
local lost = split(csv, "[^,]+")
-- lost = red, green
-- Сохраняем их: добавляем разделитель в конец и сопоставляем поле
-- вместе с разделителем
local kept = split(csv .. ",", "([^,]*),")
-- kept = red, , green
print("lst_data = "
.. table.concat(lst_data, ", "))
print("name = " .. name)
print("position = " .. position)
print("year = " .. year)
print("words = " .. table.concat(words, ", "))
print("lost = " .. table.concat(lost, ", "))
print("kept = " .. table.concat(kept, ", "))