Lua:使用gmatch条件切割字符串
2015-2-8 16:12:5
收藏:0
阅读:80
评论:0
我正在使用 Lua 编写 Mushclient 插件。Mushclient 包含了 PCRE 模块,可以使用 rex.new 函数编译正则表达式。我不确定是否需要使用它来完成我想做的事情,但我认为可能需要,尽管我宁愿不用。
基本上,我想使用分隔符“,”或“ and ”将一个字符串分割成一个表。但是,这些“分隔符”出现在我想要保留未拆分的项目内的某些情况中(例如 Felix, the Cat)。以下是我已经完成的内容:
false_separators = {"Felix, the Cat", "orange and tan cat", "black and white cat"}
separators = rex.new(" ?(.+?)(?:,| and )")
local sample_text = "a black and white cat, a tabby cat, a giant cat, Felix, the Cat and an orange and tan cat."
index = 1
matches = {}
separators:gmatch(sample_text, function (m, t)
for k, v in pairs(t) do
print(v)
table.insert(matches, v)
end
end)
这将输出:
a black
white cat
a tabby cat
a giant cat
Felix
the Cat
an orange
这有两个问题。首先,最后一个项目未包括在内。其次,我还没有想出如何实现我的 false_separators 表。我期望的输出是:
a black and white cat
a tabby cat
a giant cat
Felix, the Cat
an orange and tan cat
我可以通过大量的 gsub 处理来实现它,但这似乎不够优雅,可能有漏洞或运行缓慢:
false_separators = {"Felix, the Cat", "orange and tan cat", "black and white cat"}
local sample_text = "a black and white cat, a tabby cat, a giant cat, Felix, the Cat and an orange and tan cat."
function split_cats(text, false_sep)
for k, v in ipairs(false_sep) do
text = text:gsub(v, v:gsub(" ", "_")) -- 将误判为分隔符的匹配项中的空格替换为下划线
end
text = text:gsub(" and ", ", "):gsub(", ", ";") -- 替换 " and "(不在下划线周围的)成逗号,然后用分号替换所有不在下划线后面的逗号。分号现在是真正的分隔符。
m = utils.split (text, ";") or {} -- 用分号拆分
for i, v in ipairs(m) do
m[i] = v:gsub("_", " ") -- 删除下划线
end
return m
end
table.foreach(split_cats(sample_text, false_separators), print)
输出:
1 a black and white cat
2 a tabby cat
3 a giant cat
4 Felix, the Cat
5 an orange and tan cat.
点赞
评论区的留言会收到邮件通知哦~
推荐文章
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法