Split String and Include Delimiter in Lua

2019-09-10 11:55发布

问题:

I searched on Google and on Stack Overflow and didn't find answer for this question. Looking at the documentation I didn't find how to do this because every function that allows splits excludes the delimiter.

EDIT

for i, word in pairs(split(text, "<(.-)>")) do
    print(word)
end

function split(string, delimiter) -- Got this function from https://helloacm.com/split-a-string-in-lua/
    result = {};

    for match in (string..delimiter):gmatch("(.-)"..delimiter) do
        table.insert(result, match);
    end

    return result;
end

This code replaces the parts in the format "<(.-)>"

Example:

Input: "Hello<a>World</a>!"

Expected Output: {"Hello", "<a>", "World", "</a>", "!"}

Real Output: {"Hello", "World", "!"}

回答1:

s = "Hello<a>World</a>!"
for a in s:gsub('%b<>','\0%0\0'):gmatch'%Z+' do
  print(a)
end


回答2:

I assume this is related to HTML tags or similar.

One quick-n-dirty possibility I can think of that should cover your specific use case is this:

s = 'Hello<a>World</a>!'

function split(s)
  local ans = {}
  for a,b in (s..'<>'):gmatch '(.-)(%b<>)' do
    ans[#ans+1] = a
    ans[#ans+1] = b
  end
  ans[#ans] = nil
  return ans
end

for _,v in ipairs(split(s)) do
  print(v)
end


标签: string split lua