【问题标题】:Split String and Include Delimiter in Lua在 Lua 中拆分字符串并包含分隔符
【发布时间】:2016-03-03 18:49:39
【问题描述】:

我在 Google 和 Stack Overflow 上进行了搜索,但没有找到这个问题的答案。查看文档我没有找到如何执行此操作,因为每个允许拆分的函数都排除了分隔符。

编辑

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

此代码替换格式为“”的部分

例子:

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

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

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

【问题讨论】:

  • 也许可以试试string.gmatch
  • string.gmatch 不包括分隔符
  • string.gmatch 包含您告诉它包含的任何内容:for v in ("a, b, c, d"):gmatch("(%w+,?)") do print(v) end
  • 显示示例输入和预期输出。
  • 用一个例子和我正在使用的代码更新了问题

标签: string split lua


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

【讨论】:

    【解决方案2】:

    我认为这与 HTML 标记或类似标记有关。

    我能想到的一种快速且肮脏的可能性应该涵盖您的特定用例:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 2014-02-08
      相关资源
      最近更新 更多