使用Lua的字符串模块进行模式匹配
2009-7-22 20:45:48
收藏:0
阅读:347
评论:3
我正在尝试在 Lua 中使用 string.find
来解析用户输入字符串的内容。我试图查找最多三个不同的参数(如果用户输入了它们),但有时只有一个。
输入字符串在其更长的形式下看起来像:
local userInput = "x|y|z"
其中 x
,y
和 z
可以是任何字符或空白(空字符串,即 ""
),而 z
还可以包含垂直条/管 - 我只想基于遇到的前两个垂直杠("|"
)将字符串分成三个部分。困难在于用户也可以不使用该形式 - 他或她可以输入简单地 "x"
或 "x||z"
或 "||z"
等。在这些情况下,我仍需要获取 x
,y
和 z
的值,并且应该清楚它们分别分配给哪些变量。
例如,我尝试了这个:
local _,_,a,b,c = string.find(usermsg, "([^|]*)|?([^|]*)|?(.+)")
首先注意到这并没有正确地获取 a
,b
和 c
。但更重要的是,当 usermsg
只是 "x"
时,它将 x
的值设置为变量 c
,而不是 a
。并且当用户键入 "x|y"
时,变量 a
是 x
(正确的),但变量 c
是 y
(错误的,应该分配给变量 b
)。
然后我试图分开做:
local _,_,a = string.find(usermsg , "([^|]+)|?[^|]*|?.*")
local _,_,b= string.find(usermsg , "[^|]*|([^|]+)|?.*")
local _,_,c= string.find(usermsg , "[^|]*|[^|]*|(.+)")
但这也失败了。它匹配了 x
,但没有匹配 y
,而 c
最终变成了 y
加上管道和 z
。
任何帮助都将不胜感激。谢谢! :)
原文链接 https://stackoverflow.com/questions/1141069
点赞
stackoverflow用户95612
似乎您只是在寻找带最大分割次数的典型拆分函数。这是我的函数:
function string.split( str, delim, max, special )
if max == nil then max = -1 end
if delim == nil then delim = " " end
if special == nil then special = False end
local last, start, stop = 1
local result = {}
while max ~= 0 do
start, stop = str:find(delim, last, not special )
if start == nil then
-- 如果 max 大于 str 中分隔符的数量,则到这里结束
break
end
table.insert( result, str:sub( last, start-1 ) )
last = stop+1
max = max - 1
end
-- 添加剩余部分
table.insert( result, str:sub( last ) )
return result
end
print( ("A='%s' B='%s' C='%s'"):format(unpack( ("hello|there|world"):split('|', 2) )))
print( ("A='%s' B='%s' C='%s'"):format(unpack( ("||world"):split('|', 2) )))
print( ("A='%s' B='%s' C='%s'"):format(unpack( ("hello||world"):split('|', 2) )))
print( ("A='%s' B='%s' C='%s'"):format(unpack( ("hello|there|"):split('|', 2) )))
print( ("A='%s' B='%s' C='%s'"):format(unpack( ("hello||world|and|the|rest"):split('|', 2) )))
=>
A='hello' B='there' C='world'
A='' B='' C='world'
A='hello' B='' C='world'
A='hello' B='there' C=''
A='hello' B='' C='world|and|the|rest'
2009-07-24 21:24:41
stackoverflow用户3524201
我认为解决这个问题的最佳方案是 string.match
local a, b, c = string.match("(^|*)|(^|*)|(.*)")
^|
匹配任何不是 |
的内容, *
表示它将匹配0个或多个。
2016-09-02 18:38:32
评论区的留言会收到邮件通知哦~
推荐文章
- 如何在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中获取用户配置主目录的跨平台方法
- 如何编写 Lua 模式将字符串(嵌套数组)转换为真正的数组?
这应该可以按你想要的方式工作
local _,_,a,b = string.find(usermsg, "([^|]*)|?(.*)") local _,_,b,c = string.find(b, "([^|]*)|?(.*)")