将字符串分割成单词和单词之间的空格

我目前正在编写一个lua脚本,它接收一个字符串并将其分割成一个单词表和单词之间的空格+字符。

示例:

-- 将这个
local input = "This string, is a text!"

-- 转换成这个
local output = {
    "This", " ", "string", ", ", "is", " ", "a", " ", "text", "!"
}

我尝试使用lua的模式实现来解决这个问题,但目前还没有成功。

非常感谢任何帮助!

点赞
用户4984564
用户4984564
## 将输入拆分成单词数组

```lua
local function splitter(input)
  local result = {}
  for non_word, word, final_non_word in input:gmatch "([^%w]*)(%w+)([^%w]*)" do
    if non_word ~= '' then
      table.insert(result, non_word)
    end
    table.insert(result, word)
    if final_non_word ~= '' then
      table.insert(result, final_non_word)
    end
  end
  return result
end

这个函数将一个字符串输入拆分成单词数组。拆分规则是用非单词字符分隔,保留所有非单词字符。返回的结果是一个数组,其中包含原输入字符串拆分后的所有单词和非单词字符。

2019-07-24 09:52:35